ncw / gotemplate

Package based templating system for Go
MIT License
258 stars 28 forks source link

How could I use inner type? #10

Closed gobwas closed 6 years ago

gobwas commented 9 years ago

Hello! I have some code that looks like this:

package tpl

// template type Container(T)
type T int

type Container struct {
  field T
}

In some other place:

package tpl

//go:generate gotemplate "tpl" MyTypeContainer(otherpackage.MyType)

How could I tell to gotemplate to import otherpackage somehow? Is it possible?

Thanks anyway! )

ncw commented 9 years ago

A good question! I can think of two workarounds

First - alias the external type in your package, eg

type MyType otherpackage.MyType

The other would be to run goimports on the generated code. This will fix up missing imports. You could automate this in the go generate statements.

I think for a long term fix I should do this within the code.

gobwas commented 9 years ago

Thanks!

lvoisin commented 7 years ago

Your proposed workaround does not work, as the local MyType is a different type from otherpackage.MyType.

With go 1.9, one can declare a type alias which would work, at the price of cluttering the package namespace.

I therefore propose an additional option to gotemplate that allows the user to specify import paths to add to the generated code.

igrmk commented 6 years ago

This is fixed with PR #29. Something similar to goimports is run automatically on finishing the instantiation.