Documentation ¶
Overview ¶
Package gopoet is a library to assist with generating Go code. It includes a model of the Go language that is simpler, and thus easier to work with, than those provided by the "go/ast" and "go/types" packages. It also provides adapter methods to allow simple interoperability with elements from the "go/types" and "reflect" packages.
The Go Poet API and functionality is strongly influenced by a similar library for Java (for generating Java code) named Java Poet (https://github.com/square/javapoet).
Types ¶
TypeName is the way Go Poet represents Go types. There is API in this package for constructing TypeName instances and for converting type representations from the "go/types" and "reflect" packages to TypeName values. It includes related types for representing function signatures, struct fields, and interface methods (Signature, FieldSpec, and MethodSpec respectively).
Elements ¶
GoFile is the root type in Go Poet for building a representation of Go language elements. The GoFile represents the file itself. The FileElement (and its various concrete implementations) represent top-level declarations in the file. And types like FieldSpec, InterfaceEmbed, and InterfaceMethod represent the elements that comprise struct and interface type definitions.
Statements and expressions are not modeled by the Go Poet API, so function bodies and const and var initializers are represented with a type named CodeBlock.
Usage of Go Poet involves constructing a GoFile, filling it with elements, and then using the various WriteGoFile* methods to then translate these models into Go source code.
Imports ¶
Import statements need not be defined manually. GoFile embeds a type named Imports which assists with managing import statements. It tracks all packages that are referenced, generating import aliases as necessary in the event of conflicts. After all referenced packages have been resolved, gopoet.Imports can then generate the import statements necessary. It also provides API for re-writing various references, to adjust their package qualifier so that references to elements or types in other packages are interpolated into Go source code with the correct qualifiers.
Packages and Symbols ¶
The lowest level building blocks for the above API are representations of packages, symbols (references to named package-level elements, like consts, vars, types, and funcs), and method references (like a func symbol, but also includes a type qualifier, not just a package qualifier).
Various parts of the API provide methods for accessing/converting to these types. Under the hood, it is packages and symbols that are re-written by an Imports instance to ensure all referenced elements are rendered with the package qualifier (e.g. the package name or associated import alias).
Model Limitations ¶
Go Poet does not attempt to model Go statements and expressions or provide any way to create structured representations of function and method bodies. This is very similar to Java Poet *except* that Go Poet does not provide a custom mechanism for printing and formatting code. It instead relies on the existing facilities in the "fmt" and "text/template" packages. This package provides several types for modeling elements of the Go language that can then be referenced in code blocks (via "%s" or "%v" format specifiers or as elements of a data value rendered by a template).
The CodeBlock type and related methods include API that resembles the various Print* functions in the "fmt" package. Before these are rendered to source code, references to Go elements and types are translated to account for the import statements (and any associated aliases) for the file context into which they are being rendered. Format arguments can also include instances of reflect.Type or even items from the "go/types" package: types.Type, types.Object, and *types.Package. These types of values will result in proper references to these elements when the code is actually rendered.
Similarly, templates can be rendered, and the data value supplied to the template will be reconstructed, with any elements therein being first translated to have the right package qualifiers.
Templates ¶
As described above, code blocks (which represent function and method bodies and initializer expressions) can be rendered from templates and provided data values that the template renders.
It is also possible to completely eschew modeling generated code with various elements and to generate a file completely from a template. In this case, you can still get value from Go Poet by using a *gopoet.Imports type to track imported packages and assign aliases, and then render the resulting []gopoet.ImportSpec from your template. Furthermore, the value that the template renders can contain instances of gopoet.TypeName, gopoet.Package, and gopoet.Symbol, just like when rendering code blocks for function bodies Calling imports.QualifyTemplateData(data) will re-write the values in the data value so they are properly qualified per the imported packages. Do this before rendering the template.
One limitation of re-writing template data is that it cannot change the *types* of elements except in limited circumstances. For example, a Type from the "go/types" package cannot be converted to a gopoet.TypeName if the reference is a struct field whose type is types.Type (since gopoet.TypeName does not implement types.Type). Because of this, not all referenced types and elements can be re-written so may not be rendered correctly. For this reason, it is recommended to use gopoet.TypeName as the means of referring to types in a template data value, not types.Type or reflect.Type.
Index ¶
- Variables
- func Export(s string) string
- func Unexport(s string) string
- func WriteGoFile(w io.Writer, f *GoFile) error
- func WriteGoFiles(outFn func(path string) (io.WriteCloser, error), files ...*GoFile) error
- func WriteGoFilesToFileSystem(rootDir string, files ...*GoFile) error
- func WriteGoFilesToGoPath(files ...*GoFile) error
- type ArgType
- type CodeBlock
- func (cb *CodeBlock) AddCode(code *CodeBlock) *CodeBlock
- func (cb *CodeBlock) Print(text string) *CodeBlock
- func (cb *CodeBlock) Printf(fmt string, args ...interface{}) *CodeBlock
- func (cb *CodeBlock) Println(text string) *CodeBlock
- func (cb *CodeBlock) Printlnf(fmt string, args ...interface{}) *CodeBlock
- func (cb *CodeBlock) RenderCode(template *template.Template, data interface{}) *CodeBlock
- type ConstDecl
- type ConstSpec
- func (c *ConstSpec) Initialize(fmt string, args ...interface{}) *ConstSpec
- func (c *ConstSpec) SetComment(comment string) *ConstSpec
- func (c *ConstSpec) SetInitializer(cb *CodeBlock) *ConstSpec
- func (c *ConstSpec) SetType(t TypeNameOrSpec) *ConstSpec
- func (c *ConstSpec) String() string
- func (c *ConstSpec) SymbolAt(i int) Symbol
- func (c *ConstSpec) ToSymbol() Symbol
- type FieldSpec
- type FieldType
- type FileElement
- type FormatError
- type FuncSpec
- func (f *FuncSpec) AddArg(name string, t TypeName) *FuncSpec
- func (f *FuncSpec) AddCode(cb *CodeBlock) *FuncSpec
- func (f *FuncSpec) AddResult(name string, t TypeName) *FuncSpec
- func (f *FuncSpec) Print(text string) *FuncSpec
- func (f *FuncSpec) Printf(fmt string, args ...interface{}) *FuncSpec
- func (f *FuncSpec) Println(text string) *FuncSpec
- func (f *FuncSpec) Printlnf(fmt string, args ...interface{}) *FuncSpec
- func (f *FuncSpec) RenderCode(template *template.Template, data interface{}) *FuncSpec
- func (f *FuncSpec) SetComment(comment string) *FuncSpec
- func (f *FuncSpec) SetVariadic(isVariadic bool) *FuncSpec
- func (f *FuncSpec) String() string
- func (f *FuncSpec) ToSymbol() SymbolOrMethodRef
- func (f *FuncSpec) ToTypeName() TypeName
- type GoFile
- func (f *GoFile) AddConst(c *ConstSpec) *GoFile
- func (f *GoFile) AddElement(e FileElement) *GoFile
- func (f *GoFile) AddType(t *TypeSpec) *GoFile
- func (f *GoFile) AddVar(v *VarSpec) *GoFile
- func (f *GoFile) ElementAt(i int) FileElement
- func (f *GoFile) NumElements() int
- func (f *GoFile) Package() Package
- type ImportSpec
- type Imports
- func (i *Imports) EnsureAllTypesImported(s *Signature) *Signature
- func (i *Imports) EnsureImported(sym Symbol) Symbol
- func (i *Imports) EnsureTypeImported(n TypeName) TypeName
- func (i *Imports) ImportSpecs() []ImportSpec
- func (i *Imports) PrefixForPackage(importPath string) string
- func (i *Imports) Qualify(sym Symbol) Symbol
- func (i *Imports) QualifySignature(s *Signature) *Signature
- func (i *Imports) QualifyTemplateData(data interface{}) interface{}
- func (i *Imports) QualifyType(n TypeName) TypeName
- func (i *Imports) RegisterImport(importPath, packageName string) string
- func (i *Imports) RegisterImportForPackage(pkg Package) string
- type InterfaceElement
- type InterfaceEmbed
- type InterfaceMethod
- func (m *InterfaceMethod) AddArg(name string, t TypeName) *InterfaceMethod
- func (m *InterfaceMethod) AddResult(name string, t TypeName) *InterfaceMethod
- func (m *InterfaceMethod) SetComment(comment string) *InterfaceMethod
- func (m *InterfaceMethod) SetVariadic(isVariadic bool) *InterfaceMethod
- func (m *InterfaceMethod) String() string
- func (m *InterfaceMethod) ToMethodRef() MethodReference
- func (m *InterfaceMethod) ToTypeName() TypeName
- type MethodReference
- type MethodType
- type Package
- type ReceiverSpec
- type Signature
- type Symbol
- type SymbolOrMethodRef
- type TypeDecl
- type TypeKind
- type TypeName
- func ArrayType(t TypeName, length int64) TypeName
- func BasicType(k reflect.Kind) TypeName
- func ChannelType(t TypeName, dir reflect.ChanDir) TypeName
- func FuncType(args []ArgType, results []ArgType) TypeName
- func FuncTypeFromSig(sig *Signature) TypeName
- func FuncTypeVariadic(args []ArgType, results []ArgType) TypeName
- func InterfaceType(embeds []Symbol, methods ...MethodType) TypeName
- func MapType(k, v TypeName) TypeName
- func NamedType(sym Symbol) TypeName
- func PointerType(t TypeName) TypeName
- func SliceType(t TypeName) TypeName
- func StructType(fields ...FieldType) TypeName
- func TypeNameForGoType(t types.Type) TypeName
- func TypeNameForReflectType(t reflect.Type) TypeName
- type TypeNameOrSpec
- type TypeSpec
- type VarDecl
- type VarSpec
- func (v *VarSpec) Initialize(fmt string, args ...interface{}) *VarSpec
- func (v *VarSpec) SetComment(comment string) *VarSpec
- func (v *VarSpec) SetInitializer(cb *CodeBlock) *VarSpec
- func (v *VarSpec) SetType(t TypeNameOrSpec) *VarSpec
- func (v *VarSpec) String() string
- func (v *VarSpec) SymbolAt(i int) Symbol
- func (v *VarSpec) ToSymbol() Symbol
Constants ¶
This section is empty.
Variables ¶
var ( // IntType is the type name for the builtin "int" type. IntType = BasicType(reflect.Int) // Int8Type is the type name for the builtin "int8" type. Int8Type = BasicType(reflect.Int8) // Int16Type is the type name for the builtin "int16" type. Int16Type = BasicType(reflect.Int16) // Int32Type is the type name for the builtin "int32" type (aka "rune"). Int32Type = BasicType(reflect.Int32) // Int64Type is the type name for the builtin "int64" type. Int64Type = BasicType(reflect.Int64) // RuneType is an alias for Int32Type. RuneType = Int32Type // UintType is the type name for the builtin "uint" type. UintType = BasicType(reflect.Uint) // Uint8Type is the type name for the builtin "uint8" type (aka "byte"). Uint8Type = BasicType(reflect.Uint8) // Uint16Type is the type name for the builtin "uint16" type. Uint16Type = BasicType(reflect.Uint16) // Uint32Type is the type name for the builtin "uint32" type. Uint32Type = BasicType(reflect.Uint32) // Uint64Type is the type name for the builtin "uint64" type. Uint64Type = BasicType(reflect.Uint64) // ByteType is an alias for Uint8Type. ByteType = Uint8Type // UintptrType is the type name for the builtin "uintptr" type. UintptrType = BasicType(reflect.Uintptr) // BoolType is the type name for the builtin "bool" type. BoolType = BasicType(reflect.Bool) // StringType is the type name for the builtin "string" type. StringType = BasicType(reflect.String) // Float32Type is the type name for the builtin "float32" type. Float32Type = BasicType(reflect.Float32) // Float64Type is the type name for the builtin "float64" type. Float64Type = BasicType(reflect.Float64) // Complex64Type is the type name for the builtin "complex64" type. Complex64Type = BasicType(reflect.Complex64) // Complex128Type is the type name for the builtin "complex128" type. Complex128Type = BasicType(reflect.Complex128) // ErrorType is the type name for the builtin "error" interface. ErrorType = NamedType(Symbol{Name: "error"}) // UnsafePointerType is the type name for the unsafe.Pointer type. UnsafePointerType = NamedType(NewSymbol("unsafe", "Pointer")) )
Functions ¶
func Export ¶
Export returns an exported form of the given name. It does not try to verify that s is a valid symbol in Go nor does it check whether s is already exported. If s begins with an underscore, it will be replaced with a capital "X". If s begins with an invalid character (such as a number, which is not allowed as the first character of an identifier), the returned string will be prefixed with "X".
func Unexport ¶
Unexport returns an unexported form of the given name. It does not try to verify that s is a valid symbol in Go nor does it check whether s is already unexported.
func WriteGoFile ¶
WriteGoFile renders the given Go file to the given writer.
This process first qualifies all elements and code in the given file, to ensure that all referenced packages will be correctly represented with import statements and that all referenced packages will be rendered with the correct package name or alias.
Then this serializes the file elements and contained code into a buffer, but with no attention paid to formatting.
Finally, the "go/format" package is used to convert the generated code into the Go canonical format, which is primarily needed to clean up whitespace and indentation in the output.
The formatted code is then written to the given io.Writer.
func WriteGoFiles ¶
WriteGoFiles renders all of the given Go files, using the given function to open io.Writer instances, to which the rendered and formatted Go source is written. The function is given a Go file's path, which includes both the package path and the file's name and is expected to return a writer just for that file.
If the function returns an error for any file, this function aborts and returns the error, but it makes no effort to clean up any previously written files that may have already been written without error.
func WriteGoFilesToFileSystem ¶
WriteGoFilesToFileSystem is a convenience wrapper for WriteGoFiles that uses os.Open as the function to open a writer for each file. A full path is first computed by joining the given root directory with the file's path.
func WriteGoFilesToGoPath ¶
WriteGoFilesToGoPath is a convenience wrapper for WriteGoFilesToFileSystem that inspects the GOPATH environment variable and uses the first entry therein as the root directory for where files are to be written. If the GOPATH environment variable is empty or unset, an error is returned.
Types ¶
type ArgType ¶
ArgType represents the name and type of a function argument or result value. The name is optional, but the type is not. See Signature.
type CodeBlock ¶
type CodeBlock struct {
// contains filtered or unexported fields
}
CodeBlock represents one or more Go statements or expressions, such as for initializing a value (e.g const or var) or for the body of a function or method.
Code block contents can be constructed from fmt-like methods on the CodeBlock or by rendering a template via the RenderCode method. The format arguments supplied to Printf or Printlnf methods can be references to other Go Poet types (Package, Symbol, MethodReference, TypeName) including file elements (*ConstSpec, *VarSpec, *TypeSpec, *FuncSpec, etc). Such references will be properly qualified when the CodeBlock is rendered into generated Go code, so that references use the correct package names and aliases.
func Print ¶
Print is a convenience function that allocates a new CodeBlock and calls its Print method in one step.
func Printf ¶
Printf is a convenience function that allocates a new CodeBlock and calls its Printf method in one step.
func Println ¶
Println is a convenience function that allocates a new CodeBlock and calls its Println method in one step.
func Printlnf ¶
Printlnf is a convenience function that allocates a new CodeBlock and calls its Printlnf method in one step.
func RenderCode ¶
RenderCode is a convenience function that allocates a new CodeBlock and calls its RenderCode method in one step.
func (*CodeBlock) AddCode ¶
AddCode adds the contents of the given CodeBlock to this one. It returns the code block, for method chaining.
func (*CodeBlock) Print ¶
Print adds the given text to the code block. It returns the code block, for method chaining.
func (*CodeBlock) Printf ¶
Printf adds the given text to the code block and will properly qualify any supported types in the argument list when rendered. It returns the code block, for method chaining.
func (*CodeBlock) Println ¶
Println adds the given text to the code block, along with a trailing newline. It returns the code block, for method chaining.
func (*CodeBlock) Printlnf ¶
Printlnf adds the given text to the code block and will properly qualify any supported types in the argument list when rendered. Similar to Println, it adds a trailing newline. It returns the code block, for method chaining.
func (*CodeBlock) RenderCode ¶
RenderCode uses the given template and data object to render contents. The given data object will be re-created during rendering, if necessary, so that any supported types therein are updated to use properly qualified references. For example, a struct that includes a *TypeSpec will be re-created so that the *TypeSpec field is modified to include a package name that matches the proper import name/alias for the render context.
This method returns the code block, for method chaining.
type ConstDecl ¶
ConstDecl is a FileElement representing a declaration of one or more consts. When it has exactly one const, it is rendered like so:
const name Type = initialValue
When there are multiple consts, it is rendered differently:
const ( name1 Type = initialValue name2 Type = initialValue )
func NewConstDecl ¶
NewConstDecl creates a new declaration for the given consts.
func (*ConstDecl) AddConst ¶
AddConst adds the given const to this declaration. This method returns the const declaration, for method chaining.
func (*ConstDecl) SetComment ¶
SetComment sets the declaration comment. For declarations with multiple consts, this comment is rendered above the "const" keyword, and the comments on each ConstSpec are rendered just above each individual const. For example:
// Comment from the ConstDecl const ( // Comment from the first ConstSpec c1 = value // Comment from the second ConstSpec c2 = otherValue )
If the declaration has only a single const, then leave this comment empty and instead use the Comment field on the ConstSpec only. That will then render like so:
// Comment from the ConstSpec const c1 = value
This method returns the const declaration, for method chaining.
type ConstSpec ¶
type ConstSpec struct { Comment string Names []string Type TypeNameOrSpec Initializer *CodeBlock // contains filtered or unexported fields }
ConstSpec describes a single const expression (which can actually identify more than one const). The Names field is not optional and must have at least one value. Just like in Go source, the Type field is optional but the Initializer is not.
However, there is an exception to this rule: a const is allowed to have neither type nor initializer if it follows a const and is intended to re-use the prior const's type and initializer. This is typically used with iota expressions, like so:
const ( // This const has both type and initializer a int64 = iota+1 // These consts have neither and will re-use the above type and // initializer (relying on the fact that iota is auto-incremented // after every reference inside of a const declaration) b c d )
func (*ConstSpec) Initialize ¶
Initialize sets the initializer for this const to a CodeBlock with a single statement defined by the given format message and arguments. It is a convenient shorthand for this:
c.Initializer = gopoet.Printf(fmt, args...)
This method returns the const, for method chaining.
func (*ConstSpec) SetComment ¶
SetComment sets the comment for this const expression. See ConstDecl.SetComment for more details on how comments are rendered.
This method returns the const, for method chaining.
func (*ConstSpec) SetInitializer ¶
SetInitializer sets the initializer to the given code block. This method returns the const, for method chaining.
func (*ConstSpec) SetType ¶
func (c *ConstSpec) SetType(t TypeNameOrSpec) *ConstSpec
SetType sets the type of this const expression. This method returns the const, for method chaining.
func (*ConstSpec) String ¶
String returns a simple string representation of the const. The string representation is the same as that of the symbol returned by ToSymbol, however this method will not panic: if the var has never been associated with a file, it will return just the const's name, unqualified. Also, if this const indicates more than one const name, the returned string will be a comma-separated list of all of the symbols.
func (*ConstSpec) SymbolAt ¶
SymbolAt returns a symbol that refers to the const name at the given index. This method panics if the given index is not valid (e.g. between zero, inclusive, and len(c.Names), exclusive). This method will also panic if this const has never been added to a file since, without an associated file, the package of the symbol is unknown. It can be added to a file directly via GoFile.AddConst or indirectly by first adding to a ConstDecl which is then added to a file.
func (*ConstSpec) ToSymbol ¶
ToSymbol returns a symbol that refers to this const. This method panics if the const expression indicates more than one const name, in which case the calling code should instead use SymbolAt. This method also panics if this const has never been added to a file (see SymbolAt for more information about this).
type FieldSpec ¶
type FieldSpec struct {
Comment, Name string
Tag reflect.StructTag
Type TypeNameOrSpec
// contains filtered or unexported fields
}
FieldSpec describes a field in a struct type.
func NewField ¶
func NewField(name string, t TypeNameOrSpec) *FieldSpec
NewField creates a new field with the given name and type. An empty name indicates an anonymous field, also known as an embedded type.
func (*FieldSpec) SetComment ¶
SetComment sets the comment on the field that will be rendered in the struct definition. This method returns the field, for method chaining.
type FieldType ¶
FieldType represents a field in a TypeName whose kind is KindStruct. It details the field's name and type as well as an optional struct tag.
type FileElement ¶
type FileElement interface {
// contains filtered or unexported methods
}
FileElement is a top-level element in a Go source file. It will be a const, var, type, or func declaration. The concrete types that implement this interface are *gopoet.ConstDecl, *gopoet.VarDecl, *gopoet.TypeDecl, and *gopoet.FuncSpec.
type FormatError ¶
type FormatError struct { // The unformatted Go code. Unformatted []byte // The underlying error returned from the "go/format" package. Err error }
FormatError is the kind of error returned from the WriteGoFile method (and its variations) when the resulting rendered code has a syntax error that prevents it from being formatted by the "go/format" package. Code that gets an instance of this kind of error can examine the unformatted code to associate formatting error messages (which usually contain line and column information) with the text that induced them.
func (*FormatError) Error ¶
func (e *FormatError) Error() string
Error implements the error interface, delegating to the underlying error returned from the "go/format" package.
type FuncSpec ¶
type FuncSpec struct {
Comment, Name string
Receiver *ReceiverSpec
Signature
CodeBlock
// contains filtered or unexported fields
}
FuncSpec is a FileElement representing a func or method definition. The Name field is not optional. If the function has one or more result values in its signature, the code block body should not be empty (or the result will be Go code that doesn't compile).
If the FuncSpec has a receiver, then it is a method instead of an ordinary function.
func NewMethod ¶
func NewMethod(rcvr *ReceiverSpec, name string) *FuncSpec
NewMethod creates a new method for the given receiver and with the given name.
func (*FuncSpec) AddArg ¶
AddArg adds an argument to the signature of this func. The given name can be blank for signatures with unnamed arguments. If the signature has a mix of named and unnamed args, they will all be rendered as named, but "_" will be used for unnamed ones. This method returns the func, for method chaining.
func (*FuncSpec) AddCode ¶
AddCode adds the contents of the given CodeBlock to this function's body. It returns the func, for method chaining.
func (*FuncSpec) AddResult ¶
AddResult adds a result value to the signature of this func. The given name can be blank for signatures with unnamed results. If the signature has a mix of named and unnamed results, they will all be rendered as named, but "_" will be used for unnamed ones. This method returns the func, for method chaining.
func (*FuncSpec) Print ¶
Print adds the given text to the function's body. It returns the func, for method chaining.
func (*FuncSpec) Printf ¶
Printf adds the given text to the function body and will properly qualify any supported types in the argument list when rendered. It returns the func, for method chaining.
func (*FuncSpec) Println ¶
Println adds the given text to the function's body, along with a trailing newline. It returns the func, for method chaining.
func (*FuncSpec) Printlnf ¶
Printlnf adds the given text to the function body and will properly qualify any supported types in the argument list when rendered. Similar to Println, it adds a trailing newline. It returns the func, for method chaining.
func (*FuncSpec) RenderCode ¶
RenderCode uses the given template and data object to render contents into this function's body. See CodeBlock.RenderCode for more details. This method returns the func, for method chaining.
func (*FuncSpec) SetComment ¶
SetComment sets the comment on the function. This method returns the func, for method chaining.
func (*FuncSpec) SetVariadic ¶
SetVariadic sets whether this func's signature is variadic or not. The resulting func will be invalid if variadic is set to true but the last argument is not a slice. This method returns the interface method, for method chaining.
func (*FuncSpec) String ¶
String returns a string representation of this func that can be interpolated into a code block and be a valid reference. To that end, it is the same as string representation of the symbol returned from f.ToSymbol() if it is a non-method func (e.g. no receiver). If it is a method name, it is just the name of the method. This method will not panic: if the func has never been added to a file and this is a non-method func, the func's name will be returned, without a package qualifier.
func (*FuncSpec) ToSymbol ¶
func (f *FuncSpec) ToSymbol() SymbolOrMethodRef
ToSymbol returns a symbol or a method reference that refers to this func. If this is a normal func (no receiver) the returned value is a gopoet.Symbol. Otherwise, if it is a method, the returned value is a gopoet.MethodReference. This method panics if this type has never been added to a file since, without an associated file, the package of the symbol is unknown. It can be added to a file via GoFile.AddElement.
func (*FuncSpec) ToTypeName ¶
ToTypeName returns a type name that represents the type of this function. For normal (non-method) functions, the returned type has the same signature as the function. For methods, the returned type's signature includes an extra argument before any others that represents the method's receiver. This method panics if this is a method but it has not been added to a file since, without an associated file, the package of the receiver type is unknown. It can be added to a file via GoFile.AddElement.
type GoFile ¶
type GoFile struct { Imports // The name of the file. This should not include a path, only a file // name with a ".go" extension. Name string // Comment that appears at the top of the file, before any package doc. This // is typically a copyright or other disclaimer but can be any file comments // that should not be construed as package documentation. FileComment string // Doc comments that will appear before the package declaration. These will // be used as Go package documentation by the godoc tool and website. PackageComment string // The package name that will be used in the package declaration. PackageName string // The canonical import path which, if non-empty, will be used in an // annotation comment immediately following the package declaration. CanonicalImportPath string // contains filtered or unexported fields }
GoFile represents a Go source file. It has methods for adding Go source declarations such as consts, vars, types, and functions. When building the declarations, particularly implementation code that references other types and packages, if all references are done using instances of gopoet.Package, gopoet.Symbol, and gopoet.TypeName, then the file's imports will be managed automatically. Code that constructs a GoFile can also use the Imports methods to manually register imports where necessary.
To construct a GoFile, use the NewGoFile factory function.
func NewGoFile ¶
NewGoFile creates a new Go file with the given name and package information. The given package path is used to ensure that all referenced elements are correctly qualified: e.g. if other elements are in the same package they do not need a qualifier but other elements do need a qualifier.
The given package name will be referenced in the package statement at the top of the rendered Go source file.
func (*GoFile) AddConst ¶
AddConst adds the given const to this file. This is shorthand for wrapping the given const up into a *gopoet.ConstDecl and passing that to f.AddElement. This method returns the file, for method chaining.
func (*GoFile) AddElement ¶
func (f *GoFile) AddElement(e FileElement) *GoFile
AddElement adds the given element to this file. This method returns the file, for method chaining.
func (*GoFile) AddType ¶
AddType adds the given type to this file. This is shorthand for wrapping the given type up into a *gopoet.TypeDecl and passing that to f.AddElement. This method returns the file, for method chaining.
func (*GoFile) AddVar ¶
AddVar adds the given var to this file. This is shorthand for wrapping the given var up into a *gopoet.VarDecl and passing that to f.AddElement. This method returns the file, for method chaining.
func (*GoFile) ElementAt ¶
func (f *GoFile) ElementAt(i int) FileElement
ElementAt retrieves the top-level element at the given index. The index must be between zero (inclusive) and f.NumElements() (exclusive).
func (*GoFile) NumElements ¶
NumElements returns the number of top-level elements added to this Go file.
type ImportSpec ¶
ImportSpec describes an import statement in Go source. The spec's PackageAlias will be empty if the import statement needs no alias.
func (ImportSpec) String ¶
func (i ImportSpec) String() string
String returns a string representation of the import. It will be the import path in double-quotes. Optionally, if the package alias is not empty, it will have a prefix that indicates the alias. For example:
"some.domain.com/foo/bar" bar2 "some.domain.com/foo/bar"
The first line shows the string representation without an alias, the second line with.
type Imports ¶
type Imports struct {
// contains filtered or unexported fields
}
Imports accumulate a set of package imports, used for generating a Go source file and accumulating references to other packages. As packages are imported, they will be assigned aliases if necessary (e.g. two imported packages otherwise would have the same name/prefix).
Imports is not thread-safe.
func NewImportsFor ¶
NewImportsFor returns a new Imports where the source lives in pkgPath. So any uses of other symbols also in pkgPath will not need an import and will not use a package prefix (see EnsureImported).
func (*Imports) EnsureAllTypesImported ¶
EnsureAllTypesImported ensures that all argument and result value types in the given signature are imported and returns a new signature where all types contain the correct package prefixes. See EnsureTypeImported for more details.
func (*Imports) EnsureImported ¶
EnsureImported ensures that the given symbol is imported and returns a new symbol that has the correct package prefix (based on how the given symbol's package was imported/aliased). If the symbol is already in Imports source package then a symbol is returned whose Package has an empty Name. That way calling String() on the returned symbol will correctly elide the package prefix.
func (*Imports) EnsureTypeImported ¶
EnsureTypeImported ensures that any symbols referenced by the given type are imported and returns a new type with correct package prefixes. See EnsureImported for more details.
func (*Imports) ImportSpecs ¶
func (i *Imports) ImportSpecs() []ImportSpec
ImportSpecs returns the list of imports that have been accumulated so far, sorted lexically by import path.
func (*Imports) PrefixForPackage ¶
PrefixForPackage returns a prefix to use for qualifying symbols from the given package. This method panics if the given package was never registered.
func (*Imports) Qualify ¶
Qualify returns a new symbol that has the correct package prefix, based on how the given symbol's package was imported/aliased. This method panics if symbol's package was never registered.
func (*Imports) QualifySignature ¶
QualifySignature returns a new signature where all types contain the correct package prefixes, based on how the referenced packages were imported/aliased. This method panics if any of the referenced packages were never registered.
func (*Imports) QualifyTemplateData ¶
func (i *Imports) QualifyTemplateData(data interface{}) interface{}
QualifyTemplateData will re-create the given template data value so that any references to packages (including elements/fields/etc whose type is gopoet.Package, gopoet.TypeName, gopoet.Signature, or any of the various gopoet.FileElement concrete types) indicate the correct package prefixes based on how the packages were actually imported/aliased.
If any references are found to packages that have not been imported, they are added to the imports (e.g. i.RegisterImportForPackage) and the resulting package name or alias is used to re-create the reference.
func (*Imports) QualifyType ¶
QualifyType returns a new type with correct package prefixes, based on how referenced type elements were actually imported/aliased. This method panics if any of the referenced packages were never registered.
func (*Imports) RegisterImport ¶
RegisterImport "imports" the specified package and returns the package prefix to use for symbols in the imported package. It is safe to import the same package repeatedly -- the same prefix will be returned every time. If an attempt is made to import the Imports source package (i.e. importing a package into itself), nothing will be done and an empty prefix will be returned. So such an action is safe and the returned prefix is correct for how symbols in the package should be referenced.
func (*Imports) RegisterImportForPackage ¶
RegisterImportForPackage "imports" the specified package and returns the package prefix to use for symbols in the imported package. See RegisterImport for more details.
type InterfaceElement ¶
type InterfaceElement interface {
// contains filtered or unexported methods
}
InterfaceElement is an element inside of an interface definition. This can be either an embedded interface or a method, represented by the InterfaceEmbed and InterfaceMethod types, respectively.
type InterfaceEmbed ¶
InterfaceEmbed is an embedded interface inside of an interface definition.
func NewInterfaceEmbed ¶
func NewInterfaceEmbed(s Symbol) *InterfaceEmbed
NewInterfaceEmbed returns an embedded interface for the interface type named by the given symbol.
func (*InterfaceEmbed) SetComment ¶
func (e *InterfaceEmbed) SetComment(comment string) *InterfaceEmbed
SetComment sets the comment on this embedded interface that will be rendered in the interface definition. This method returns the embed, for method chaining.
func (*InterfaceEmbed) String ¶
func (e *InterfaceEmbed) String() string
String returns a string representation of this embedded interface, which is the same as the string representation of the referenced symbol.
type InterfaceMethod ¶
type InterfaceMethod struct {
Comment, Name string
Signature
// contains filtered or unexported fields
}
InterfaceMethod is a method defined inside of an interface. This represents an explicit method, as opposed to an interface method that comes from an embedded interface.
func NewInterfaceMethod ¶
func NewInterfaceMethod(name string) *InterfaceMethod
NewInterfaceMethod returns a method with the given name.
func (*InterfaceMethod) AddArg ¶
func (m *InterfaceMethod) AddArg(name string, t TypeName) *InterfaceMethod
AddArg adds an argument to the signature of this method. The given name can be blank for signatures with unnamed arguments. If the signature has a mix of named and unnamed args, they will all be rendered as named, but "_" will be used for unnamed ones. This method returns the interface method, for method chaining.
func (*InterfaceMethod) AddResult ¶
func (m *InterfaceMethod) AddResult(name string, t TypeName) *InterfaceMethod
AddResult adds a result value to the signature of this method. The given name can be blank for signatures with unnamed results. If the signature has a mix of named and unnamed results, they will all be rendered as named, but "_" will be used for unnamed ones. This method returns the interface method, for method chaining.
func (*InterfaceMethod) SetComment ¶
func (m *InterfaceMethod) SetComment(comment string) *InterfaceMethod
SetComment sets the comment on this interface method that will be rendered in the interface definition. This returns the interface method, for call chaining.
func (*InterfaceMethod) SetVariadic ¶
func (m *InterfaceMethod) SetVariadic(isVariadic bool) *InterfaceMethod
SetVariadic sets whether this method's signature is variadic or not. The resulting interface method will be invalid if variadic is set to true but the last argument is not a slice. This method returns the interface method, for method chaining.
func (*InterfaceMethod) String ¶
func (m *InterfaceMethod) String() string
String returns the method's name, so if the interface method is used as a format argument in a code block it will result in a reference to the method, like for a method invocation.
func (*InterfaceMethod) ToMethodRef ¶
func (m *InterfaceMethod) ToMethodRef() MethodReference
ToMethodRef returns a method reference that can be interpolated into a code block to form a method expression in code.
func (*InterfaceMethod) ToTypeName ¶
func (m *InterfaceMethod) ToTypeName() TypeName
ToTypeName returns a type name with the same type as this method. The signature of the returned type varies from this interface method in that it will have an extra argument at the beginning of the argument list: the method's receiver type.
type MethodReference ¶
MethodReference is a reference to a method that can be used as a method expression in a code block. A method expression is one that references a method without a receiver, and the expression's type is a function type where the first argument is the method's receiver. For example:
bytes.Buffer.Write
This is a reference to the Write method for the Buffer type in the "bytes" standard package.
func (MethodReference) String ¶
func (r MethodReference) String() string
String returns the method reference as could be used in Go code as a method expression. It is the type's string representation followed by a dot '.' and then followed by the method name.
type MethodType ¶
MethodType represents a method in a TypeName whose kind is KindInterface. It details the method's name and signature.
type Package ¶
type Package struct {
ImportPath, Name string
}
Package is a simple representation of a Go package. The name may actually be an effective alias (when the package is imported using an alias). A symbol whose package has an empty Name is a local symbol: in the same package as the referencing context (and thus needs no package prefix to reference that symbol).
func NewPackage ¶
NewPackage is a simple factory method for a package whose name is the same as the base name (e.g. last element) of its import path.
If the package name varies from its import path, use a struct initializer instead:
Package{Name: "foo", ImportPath: "some.domain.com/foo/v1"}
If you do not know the package name, only the import path, then use a struct initializer and leave the Name field empty. An empty Name field will cause an alias to be used when the package is registered with an *Imports, to ensure that the resulting code will compile and uses a correct package prefix.
func PackageForGoType ¶
PackageForGoType returns a Package for the given Go types package. This is useful for converting between package representations.
func (Package) String ¶
String returns the package's name. While this is not always useful (the import path is generally more useful), it is the least surprising behavior if you reference the package instance from a code block:
gopoet.Printf("%s.Foobar", pkg)
In this example, the result is a qualified reference, such as "pkg.Foobar" if the given package's name were "pkg".
type ReceiverSpec ¶
ReceiverSpec describes the receiver for a method definition. Unlike an InterfaceMethod, a FuncSpec that represents a method must have explicit receiver information. The receiver must reference a named type and can be a pointer or not. Since the method must be defined in the same package as the type, the receiver need not be a fully-qualified symbol, so a string suffices (vs. a gopoet.Symbol, *gopoet.TypeSpec, or gopoet.TypeName).
func NewPointerReceiver ¶
func NewPointerReceiver(name, rcvrType string) *ReceiverSpec
NewPointerReceiver returns a new receiver definition with the given name whose receiver type is a pointer to the given type. The type is an unqualified reference to a named type in the same package.
func NewPointerReceiverForType ¶
func NewPointerReceiverForType(name string, rcvrType TypeNameOrSpec) *ReceiverSpec
NewPointerReceiverForType returns a new receiver definition with the given name whose receiver type is a pointer to the given type. If the given receiver type is not a named type, this method will panic.
func NewReceiver ¶
func NewReceiver(name, rcvrType string) *ReceiverSpec
NewReceiver returns a new receiver definition with the given name and the given type. The type is an unqualified reference to a named type in the same package.
func NewReceiverForType ¶
func NewReceiverForType(name string, rcvrType TypeNameOrSpec) *ReceiverSpec
NewReceiverForType returns a new receiver definition with the given name and the given receiver type. If the given receiver type is not a named type or a pointer to a named type, this method will panic.
type Signature ¶
Signature represents a function signature, which includes the types of the arguments and return values. If the last argument is a slice, the function might also be variadic or not.
Signatures do not carry receiver information for methods. In the case of MethodType instances, the receiver is implied by the enclosing TypeName. For FuncSpec instances, the receiver is a separate field of the FuncSpec, distinct from the signature.
func (*Signature) AddArg ¶
AddArg adds an argument to the signature. The given name can be blank for signatures with unnamed arguments. If the signature has a mix of named and unnamed args, they will all be rendered as named, but "_" will be used for unnamed ones. This method returns the signature, for method chaining.
func (*Signature) AddResult ¶
AddResult adds a result value to the signature. The given name can be blank for signatures with unnamed results. If the signature has a mix of named and unnamed results, they will all be rendered as named, but "_" will be used for unnamed ones. This method returns the signature, for method chaining.
func (*Signature) SetVariadic ¶
SetVariadic sets whether this signature represents a variadic function or not. The resulting signature will be invalid if variadic is set to true but the last argument is not a slice. This method returns the signature, for method chaining.
type Symbol ¶
Symbol references an element in Go source. It is a const, var, function, or type.
type SymbolOrMethodRef ¶
SymbolOrMethodRef is either a Symbol or a MethodReference (either of which can refer to an element in a Go source file).
func SymbolForGoObject ¶
func SymbolForGoObject(obj types.Object) SymbolOrMethodRef
SymbolForGoObject returns the given Go types object as a gopoet.Symbol or as a gopoet.MethodReference. If the given object is a method, it returns a method reference. Otherwise (const, var, type, non-method func), the returned value is a symbol.
type TypeDecl ¶
TypeDecl is a FileElement representing a declaration of one or more types. When it has exactly one type, it is rendered like so:
type Name underlyingType
When there are multiple types, it is rendered differently:
type ( Name1 underlyingType1 name2 underlyingType2 )
func NewTypeDecl ¶
NewTypeDecl creates a new declaration for the given types.
func (*TypeDecl) AddType ¶
AddType adds the given type to this declaration. This method returns the type declaration, for method chaining.
func (*TypeDecl) SetComment ¶
SetComment sets the declaration comment. For declarations with multiple types, this comment is rendered above the "type" keyword, and the comments on each TypeSpec are rendered just above each individual type. For example:
// Comment from the TypeDecl type ( // Comment from the first TypeSpec T1 int // Comment from the second TypeSpec T2 string )
If the declaration has only a single type, then leave this comment empty and instead use the Comment field on the TypeSpec only. That will then render like so:
// Comment from the TypeSpec type T1 int
This method returns the type declaration, for method chaining.
type TypeKind ¶
type TypeKind int
TypeKind is an enumeration of the allowed categories of TypeNames.
const ( // KindInvalid is not a valid kind. A valid TypeName will return a non-zero // kind. KindInvalid TypeKind = iota // KindNamed indicates a named type. The only information available in the // TypeName is the package and name of the type, not its underlying type. // The type's Symbol() method can be used to get the details of the name. KindNamed // KindBasic indicates an unnamed basic type (i.e. primitive). The type's // BasicKind() method can be used to determine which basic type it is. // // Note that though the "go/types" package considers an unsafe.Pointer to be // a basic type, this package does not. An unsafe.Pointer will instead be // represented by a TypeName that is a named type whose symbol indicates // "unsafe" as the package and "Pointer" as the element name. KindBasic // KindPtr indicates is a pointer. The type's Elem() method can be used to // determine the type to which it points. KindPtr // KindSlice indicates a slice. The type's Elem() method can be used to // determine the slice's element type. KindSlice // KindArray indicates an array. The type's Elem() and Len() methods can be // used to determine array's element type and length, respectively. KindArray // KindMap indicates a map. The type's Key() and Elem() methods can be used // to determine the map's key and value types, respectively. KindMap // KindChan indicates a chan. The type's Elem() and Dir() methods can be // used to determine the element type and channel direction, respectively. KindChan // KindFunc indicates a func. The type's Signature() method can be used to // inspect the function's signature, including argument and result types. KindFunc // KindStruct indicates a struct type. The type's Fields() method can be // used to interrogate details about the struct. This kind is only returned // for type names that represent unnamed struct types. KindStruct // KindInterface indicates an interface type. The type's Methods() and // Embeds() methods can be used to determine the explicit methods and // the embedded interfaces, respectively. This kind is only returned for // type names that represent unnamed interface types. KindInterface )
type TypeName ¶
type TypeName interface { fmt.Stringer // Kind returns the kind of type this instance represents. Kind() TypeKind // Symbol returns the symbol that this named type represents, or a zero // value symbol (empty name) if this type name does not represent a named // type. Symbol() Symbol // Elem returns this instance's element type. This is applicable only to // pointer, slice, array, map, and channel type names. For map type names, // the element type is the type of values in the map. For type names that // are not applicable, it returns nil Elem() TypeName // Key returns this instance's key type, or nil if this type name does not // represent a map type. Key() TypeName // Len returns the size of this array type, or -1 if this type name does // not represent an array. Len() int64 // Dir returns the direction of this channel type, or zero if this type // does not represent an array. Dir() reflect.ChanDir // BasicKind returns the kind of scalar/basic type this instance represents, // or reflect.Invalid if this type name does not represent a basic type. BasicKind() reflect.Kind // Signature returns the signature of this function or nil if this type // name does represent a function type. Signature() *Signature // Fields returns the fields of this struct type or nil if this type name // does not represent a struct type. Named struct types will return a kind // of KindNamed and nil from this method; only unnamed struct types will // contain field information. Fields() []FieldType // Methods returns the explicit methods of this interface type or nil if // this type name does not represent an interface type. Named interface // types will return a kind of KindNamed and nil from this method; only // unnamed interface types will contain method information. Methods() []MethodType // Embeds returns the symbols for the named interfaces that this interface // type embeds or nil if this type name does not represent an interface // type. Named interface types will return a kind of KindNamed and nil from // this method; only unnamed interface types will contain embedded interface // information. Embeds() []Symbol // contains filtered or unexported methods }
TypeName represents a Go type, nominally. It is suitable for rendering a type use in source. However, it is not sufficient for doing type analysis or for defining a type as named types only refer to their package and name, not the underlying type.
func ArrayType ¶
ArrayType returns a TypeName that represents an array whose elements are of the given type and that has the given length.
func BasicType ¶
BasicType returns a TypeName for the given basic kind. If the given kind is reflect.UnsafePointer, a named type is returned whose symbol represents the "unsafe.Pointer" name. Other kinds result in a basic type. If the given kind is not valid for a basic type (e.g. map, slice, array, chan, func, struct, or interface), this function will panic.
func ChannelType ¶
ChannelType returns a TypeName that represents a channel whose elements are of the given type and that has the given direction. If a direction of 0 is provided, the returned channel will be bi-directional.
func FuncType ¶
FuncType returns a TypeName that represents a non-variadic function with the given argument and result value types.
func FuncTypeFromSig ¶
FuncTypeFromSig returns a TypeName that represents a function with the given signature.
func FuncTypeVariadic ¶
FuncTypeVariadic returns a TypeName that represents a variadic function with the given argument and result value types. If the last argument type given is not a slice, the returned function type is invalid.
func InterfaceType ¶
func InterfaceType(embeds []Symbol, methods ...MethodType) TypeName
InterfaceType returns a TypeName that represents an unnamed interface type with the given embedded interfaces and explicit methods.
func MapType ¶
MapType returns a TypeName that represents a map whose keys and values are of the given types.
func NamedType ¶
NamedType returns a TypeName that represents a named type where the given symbol is the type's qualified name.
func PointerType ¶
PointerType returns a TypeName that represents a pointer to the given type.
func SliceType ¶
SliceType returns a TypeName that represents a slice whose elements are of the given type.
func StructType ¶
StructType returns a TypeName that represents an unnamed struct type with the given fields.
func TypeNameForGoType ¶
TypeNameForGoType converts the given "go/types" type into a TypeName.
func TypeNameForReflectType ¶
TypeNameForReflectType converts the given reflect.Type into a TypeName. Note that reflect.Type instances do not carry information about embedded interfaces, for unnamed interface types. So the resulting TypeName will contain all methods as if they were all explicit, even if some come from embedded interfaces in the type's source definition.
type TypeNameOrSpec ¶
type TypeNameOrSpec interface {
// contains filtered or unexported methods
}
TypeNameOrSpec represents a type and can either be a TypeName instance or a *TypeSpec. The former allows creating arbitrary type references whereas the latter allows referencing type elements whose definitions are also being generated.
A *TypeSpec also allows for defining comments on struct fields and interface methods, for unnamed structs and interfaces, whereas a TypeName does not (a TypeName has only type information, no other source-level information).
type TypeSpec ¶
type TypeSpec struct {
Comment, Name string
// contains filtered or unexported fields
}
TypeSpec describes a single type. The underlying type is not optional and not exported, so the only way to create a valid *TypeSpec is using the various factory methods (NewTypeSpec, NewTypeAlias, NewStructTypeSpec, and NewInterfaceTypeSpec).
func NewInterfaceTypeSpec ¶
func NewInterfaceTypeSpec(typeName string, elements ...InterfaceElement) *TypeSpec
NewInterfaceTypeSpec creates a new type spec for an interface with the given name and given elements (explicit methods and embedded interfaces).
func NewStructTypeSpec ¶
NewStructTypeSpec creates a new type spec for a struct with the given name and given fields.
func NewTypeAlias ¶
func NewTypeAlias(typeName string, t TypeNameOrSpec) *TypeSpec
NewTypeAlias creates a new type spec that aliases the given type to the given name.
func NewTypeSpec ¶
func NewTypeSpec(typeName string, t TypeNameOrSpec) *TypeSpec
NewTypeSpec creates a new type spec that declares the given name to have the given underlying type.
func (*TypeSpec) IsAlias ¶
IsAlias returns true if this is a type alias, vs. a regular type definition.
func (*TypeSpec) SetComment ¶
SetComment sets the comment for this type. See TypeDecl.SetComment for more details on how comments are rendered.
This method returns the type, for method chaining.
func (*TypeSpec) String ¶
String returns a simple string representation of the type. The string representation is the same as that of the type name returned by ToTypeName.
However this method will not panic: if this is a named type that has never been associated with a file, it will return just the type's name, unqualified.
func (*TypeSpec) ToSymbol ¶
ToSymbol returns a symbol that refers to this type. This method panics if this is an unnamed type. This method also panics if this type has never been added to a file since, without an associated file, the package of the symbol is unknown. It can be added to a file directly via GoFile.AddType or indirectly by first adding to a TypeDecl which is then added to a file.
func (*TypeSpec) ToTypeName ¶
ToTypeName returns a TypeName that represents this type. If this is a named type, the returned TypeName will have a kind of KindNamed. If this is not a named type then this is the same as calling t.Underlying().
If this is a named type, it will panic if the type has not been added to a file. (See ToSymbol for more details on this constraint.)
func (*TypeSpec) Underlying ¶
Underlying returns the underlying type for this named type. If this type is unnamed, this is the same as calling t.ToTypeName().
type VarDecl ¶
VarDecl is a FileElement representing a declaration of one or more vars. When it has exactly one var, it is rendered like so:
var name Type = initialValue
When there are multiple vars, it is rendered differently:
var ( name1 Type = initialValue name2 Type = initialValue )
func NewVarDecl ¶
NewVarDecl creates a new declaration for the given vars.
func (*VarDecl) AddVar ¶
AddVar adds the given var to this declaration. This method returns the var declaration, for method chaining.
func (*VarDecl) SetComment ¶
SetComment sets the declaration comment. For declarations with multiple vars, this comment is rendered above the "var" keyword, and the comments on each VarSpec are rendered just above each individual var. For example:
// Comment from the VarDecl var ( // Comment from the first VarSpec v1 = value // Comment from the second VarSpec v2 = otherValue )
If the declaration has only a single var, then leave this comment empty and instead use the Comment field on the VarSpec only. That will then render like so:
// Comment from the VarSpec var v1 = value
This method returns the var declaration, for method chaining.
type VarSpec ¶
type VarSpec struct { Comment string Names []string Type TypeNameOrSpec Initializer *CodeBlock // contains filtered or unexported fields }
VarSpec describes a single var expression (which can actually identify more than one var). The Names field is not optional and must have at least one value. Just like in Go source, the Type field is optional only if the Initializer is set (in which case, the type is inferred from the type of the initializer expression). One or the other, or both, must be present.
func (*VarSpec) Initialize ¶
Initialize sets the initializer for this var to a CodeBlock with a single statement defined by the given format message and arguments. It is a convenient shorthand for this:
v.Initializer = gopoet.Printf(fmt, args...)
This method returns the var, for method chaining.
func (*VarSpec) SetComment ¶
SetComment sets the comment for this var expression. See VarDecl.SetComment for more details on how comments are rendered.
This method returns the var, for method chaining.
func (*VarSpec) SetInitializer ¶
SetInitializer sets the initializer to the given code block. This method returns the var, for method chaining.
func (*VarSpec) SetType ¶
func (v *VarSpec) SetType(t TypeNameOrSpec) *VarSpec
SetType sets the type of this var. This method returns the var, for method chaining.
func (*VarSpec) String ¶
String returns a simple string representation of the var. The string representation is the same as that of the symbol returned by ToSymbol, however this method will not panic: if the var has never been associated with a file, it will return just the var's name, unqualified. Also, if this var indicates more than one var name, the returned string will be a comma-separated list of all of the symbols.
func (*VarSpec) SymbolAt ¶
SymbolAt returns a symbol that refers to the var name at the given index. This method panics if the given index is not valid (e.g. between zero, inclusive, and len(v.Names), exclusive). This method will also panic if this var has never been added to a file since, without an associated file, the package of the symbol is unknown. It can be added to a file directly via GoFile.AddVar or indirectly by first adding to a VarDecl which is then added to a file.
func (*VarSpec) ToSymbol ¶
ToSymbol returns a symbol that refers to this var. This method panics if the var expression indicates more than one var name, in which case calling code should instead use SymbolAt. This method also panics if this var has never been added to a file (see SymbolAt for more information about this).