Documentation ¶
Overview ¶
Package jen is a code generator for Go
Index ¶
- func IsReservedWord(alias string) bool
- type Code
- type Dict
- type File
- func (f *File) Anon(paths ...string)
- func (f *File) CgoPreamble(comment string)
- func (f *File) GoString() string
- func (f *File) HeaderComment(comment string)
- func (f *File) ImportAlias(path, alias string)
- func (f *File) ImportName(path, name string)
- func (f *File) ImportNames(names map[string]string)
- func (f *File) PackageComment(comment string)
- func (f *File) Render(w io.Writer) error
- func (f *File) Save(filename string) error
- type Group
- func (g *Group) Add(code ...Code) *Statement
- func (g *Group) Append(args ...Code) *Statement
- func (g *Group) AppendFunc(f func(*Group)) *Statement
- func (g *Group) Assert(typ Code) *Statement
- func (g *Group) Block(statements ...Code) *Statement
- func (g *Group) BlockFunc(f func(*Group)) *Statement
- func (g *Group) Bool() *Statement
- func (g *Group) Break() *Statement
- func (g *Group) Byte() *Statement
- func (g *Group) Call(params ...Code) *Statement
- func (g *Group) CallFunc(f func(*Group)) *Statement
- func (g *Group) Cap(v Code) *Statement
- func (g *Group) Case(cases ...Code) *Statement
- func (g *Group) CaseFunc(f func(*Group)) *Statement
- func (g *Group) Chan() *Statement
- func (g *Group) Close(c Code) *Statement
- func (g *Group) Comment(str string) *Statement
- func (g *Group) Commentf(format string, a ...interface{}) *Statement
- func (g *Group) Complex(r Code, i Code) *Statement
- func (g *Group) Complex128() *Statement
- func (g *Group) Complex64() *Statement
- func (g *Group) Const() *Statement
- func (g *Group) Continue() *Statement
- func (g *Group) Copy(dst Code, src Code) *Statement
- func (g *Group) Custom(options Options, statements ...Code) *Statement
- func (g *Group) CustomFunc(options Options, f func(*Group)) *Statement
- func (g *Group) Default() *Statement
- func (g *Group) Defer() *Statement
- func (g *Group) Defs(definitions ...Code) *Statement
- func (g *Group) DefsFunc(f func(*Group)) *Statement
- func (g *Group) Delete(m Code, key Code) *Statement
- func (g *Group) Do(f func(*Statement)) *Statement
- func (g *Group) Dot(name string) *Statement
- func (g *Group) Else() *Statement
- func (g *Group) Empty() *Statement
- func (g *Group) Err() *Statement
- func (g *Group) Error() *Statement
- func (g *Group) Fallthrough() *Statement
- func (g *Group) False() *Statement
- func (g *Group) Float32() *Statement
- func (g *Group) Float64() *Statement
- func (g *Group) For(conditions ...Code) *Statement
- func (g *Group) ForFunc(f func(*Group)) *Statement
- func (g *Group) Func() *Statement
- func (g *Group) Go() *Statement
- func (g *Group) GoString() string
- func (g *Group) Goto() *Statement
- func (g *Group) Id(name string) *Statement
- func (g *Group) If(conditions ...Code) *Statement
- func (g *Group) IfFunc(f func(*Group)) *Statement
- func (g *Group) Imag(c Code) *Statement
- func (g *Group) Index(items ...Code) *Statement
- func (g *Group) IndexFunc(f func(*Group)) *Statement
- func (g *Group) Int() *Statement
- func (g *Group) Int16() *Statement
- func (g *Group) Int32() *Statement
- func (g *Group) Int64() *Statement
- func (g *Group) Int8() *Statement
- func (g *Group) Interface(methods ...Code) *Statement
- func (g *Group) InterfaceFunc(f func(*Group)) *Statement
- func (g *Group) Iota() *Statement
- func (g *Group) Len(v Code) *Statement
- func (g *Group) Line() *Statement
- func (g *Group) List(items ...Code) *Statement
- func (g *Group) ListFunc(f func(*Group)) *Statement
- func (g *Group) Lit(v interface{}) *Statement
- func (g *Group) LitByte(v byte) *Statement
- func (g *Group) LitByteFunc(f func() byte) *Statement
- func (g *Group) LitFunc(f func() interface{}) *Statement
- func (g *Group) LitRune(v rune) *Statement
- func (g *Group) LitRuneFunc(f func() rune) *Statement
- func (g *Group) Make(args ...Code) *Statement
- func (g *Group) Map(typ Code) *Statement
- func (g *Group) New(typ Code) *Statement
- func (g *Group) Nil() *Statement
- func (g *Group) Null() *Statement
- func (g *Group) Op(op string) *Statement
- func (g *Group) Panic(v Code) *Statement
- func (g *Group) Params(params ...Code) *Statement
- func (g *Group) ParamsFunc(f func(*Group)) *Statement
- func (g *Group) Parens(item Code) *Statement
- func (g *Group) Print(args ...Code) *Statement
- func (g *Group) PrintFunc(f func(*Group)) *Statement
- func (g *Group) Println(args ...Code) *Statement
- func (g *Group) PrintlnFunc(f func(*Group)) *Statement
- func (g *Group) Qual(path, name string) *Statement
- func (g *Group) Range() *Statement
- func (g *Group) Real(c Code) *Statement
- func (g *Group) Recover() *Statement
- func (g *Group) Render(writer io.Writer) error
- func (g *Group) RenderWithFile(writer io.Writer, file *File) error
- func (g *Group) Return(results ...Code) *Statement
- func (g *Group) ReturnFunc(f func(*Group)) *Statement
- func (g *Group) Rune() *Statement
- func (g *Group) Select() *Statement
- func (g *Group) String() *Statement
- func (g *Group) Struct(fields ...Code) *Statement
- func (g *Group) StructFunc(f func(*Group)) *Statement
- func (g *Group) Switch(conditions ...Code) *Statement
- func (g *Group) SwitchFunc(f func(*Group)) *Statement
- func (g *Group) Tag(items map[string]string) *Statement
- func (g *Group) True() *Statement
- func (g *Group) Type() *Statement
- func (g *Group) Uint() *Statement
- func (g *Group) Uint16() *Statement
- func (g *Group) Uint32() *Statement
- func (g *Group) Uint64() *Statement
- func (g *Group) Uint8() *Statement
- func (g *Group) Uintptr() *Statement
- func (g *Group) Values(values ...Code) *Statement
- func (g *Group) ValuesFunc(f func(*Group)) *Statement
- func (g *Group) Var() *Statement
- type Options
- type Statement
- func Add(code ...Code) *Statement
- func Append(args ...Code) *Statement
- func AppendFunc(f func(*Group)) *Statement
- func Assert(typ Code) *Statement
- func Block(statements ...Code) *Statement
- func BlockFunc(f func(*Group)) *Statement
- func Bool() *Statement
- func Break() *Statement
- func Byte() *Statement
- func Call(params ...Code) *Statement
- func CallFunc(f func(*Group)) *Statement
- func Cap(v Code) *Statement
- func Case(cases ...Code) *Statement
- func CaseFunc(f func(*Group)) *Statement
- func Chan() *Statement
- func Close(c Code) *Statement
- func Comment(str string) *Statement
- func Commentf(format string, a ...interface{}) *Statement
- func Complex(r Code, i Code) *Statement
- func Complex128() *Statement
- func Complex64() *Statement
- func Const() *Statement
- func Continue() *Statement
- func Copy(dst Code, src Code) *Statement
- func Custom(options Options, statements ...Code) *Statement
- func CustomFunc(options Options, f func(*Group)) *Statement
- func Default() *Statement
- func Defer() *Statement
- func Defs(definitions ...Code) *Statement
- func DefsFunc(f func(*Group)) *Statement
- func Delete(m Code, key Code) *Statement
- func Do(f func(*Statement)) *Statement
- func Dot(name string) *Statement
- func Else() *Statement
- func Empty() *Statement
- func Err() *Statement
- func Error() *Statement
- func Fallthrough() *Statement
- func False() *Statement
- func Float32() *Statement
- func Float64() *Statement
- func For(conditions ...Code) *Statement
- func ForFunc(f func(*Group)) *Statement
- func Func() *Statement
- func Go() *Statement
- func Goto() *Statement
- func Id(name string) *Statement
- func If(conditions ...Code) *Statement
- func IfFunc(f func(*Group)) *Statement
- func Imag(c Code) *Statement
- func Index(items ...Code) *Statement
- func IndexFunc(f func(*Group)) *Statement
- func Int() *Statement
- func Int16() *Statement
- func Int32() *Statement
- func Int64() *Statement
- func Int8() *Statement
- func Interface(methods ...Code) *Statement
- func InterfaceFunc(f func(*Group)) *Statement
- func Iota() *Statement
- func Len(v Code) *Statement
- func Line() *Statement
- func List(items ...Code) *Statement
- func ListFunc(f func(*Group)) *Statement
- func Lit(v interface{}) *Statement
- func LitByte(v byte) *Statement
- func LitByteFunc(f func() byte) *Statement
- func LitFunc(f func() interface{}) *Statement
- func LitRune(v rune) *Statement
- func LitRuneFunc(f func() rune) *Statement
- func Make(args ...Code) *Statement
- func Map(typ Code) *Statement
- func New(typ Code) *Statement
- func Nil() *Statement
- func Null() *Statement
- func Op(op string) *Statement
- func Panic(v Code) *Statement
- func Params(params ...Code) *Statement
- func ParamsFunc(f func(*Group)) *Statement
- func Parens(item Code) *Statement
- func Print(args ...Code) *Statement
- func PrintFunc(f func(*Group)) *Statement
- func Println(args ...Code) *Statement
- func PrintlnFunc(f func(*Group)) *Statement
- func Qual(path, name string) *Statement
- func Range() *Statement
- func Real(c Code) *Statement
- func Recover() *Statement
- func Return(results ...Code) *Statement
- func ReturnFunc(f func(*Group)) *Statement
- func Rune() *Statement
- func Select() *Statement
- func String() *Statement
- func Struct(fields ...Code) *Statement
- func StructFunc(f func(*Group)) *Statement
- func Switch(conditions ...Code) *Statement
- func SwitchFunc(f func(*Group)) *Statement
- func Tag(items map[string]string) *Statement
- func True() *Statement
- func Type() *Statement
- func Uint() *Statement
- func Uint16() *Statement
- func Uint32() *Statement
- func Uint64() *Statement
- func Uint8() *Statement
- func Uintptr() *Statement
- func Values(values ...Code) *Statement
- func ValuesFunc(f func(*Group)) *Statement
- func Var() *Statement
- func (s *Statement) Add(code ...Code) *Statement
- func (s *Statement) Append(args ...Code) *Statement
- func (s *Statement) AppendFunc(f func(*Group)) *Statement
- func (s *Statement) Assert(typ Code) *Statement
- func (s *Statement) Block(statements ...Code) *Statement
- func (s *Statement) BlockFunc(f func(*Group)) *Statement
- func (s *Statement) Bool() *Statement
- func (s *Statement) Break() *Statement
- func (s *Statement) Byte() *Statement
- func (s *Statement) Call(params ...Code) *Statement
- func (s *Statement) CallFunc(f func(*Group)) *Statement
- func (s *Statement) Cap(v Code) *Statement
- func (s *Statement) Case(cases ...Code) *Statement
- func (s *Statement) CaseFunc(f func(*Group)) *Statement
- func (s *Statement) Chan() *Statement
- func (s *Statement) Clone() *Statement
- func (s *Statement) Close(c Code) *Statement
- func (s *Statement) Comment(str string) *Statement
- func (s *Statement) Commentf(format string, a ...interface{}) *Statement
- func (s *Statement) Complex(r Code, i Code) *Statement
- func (s *Statement) Complex128() *Statement
- func (s *Statement) Complex64() *Statement
- func (s *Statement) Const() *Statement
- func (s *Statement) Continue() *Statement
- func (s *Statement) Copy(dst Code, src Code) *Statement
- func (s *Statement) Custom(options Options, statements ...Code) *Statement
- func (s *Statement) CustomFunc(options Options, f func(*Group)) *Statement
- func (s *Statement) Default() *Statement
- func (s *Statement) Defer() *Statement
- func (s *Statement) Defs(definitions ...Code) *Statement
- func (s *Statement) DefsFunc(f func(*Group)) *Statement
- func (s *Statement) Delete(m Code, key Code) *Statement
- func (s *Statement) Do(f func(*Statement)) *Statement
- func (s *Statement) Dot(name string) *Statement
- func (s *Statement) Else() *Statement
- func (s *Statement) Empty() *Statement
- func (s *Statement) Err() *Statement
- func (s *Statement) Error() *Statement
- func (s *Statement) Fallthrough() *Statement
- func (s *Statement) False() *Statement
- func (s *Statement) Float32() *Statement
- func (s *Statement) Float64() *Statement
- func (s *Statement) For(conditions ...Code) *Statement
- func (s *Statement) ForFunc(f func(*Group)) *Statement
- func (s *Statement) Func() *Statement
- func (s *Statement) Go() *Statement
- func (s *Statement) GoString() string
- func (s *Statement) Goto() *Statement
- func (s *Statement) Id(name string) *Statement
- func (s *Statement) If(conditions ...Code) *Statement
- func (s *Statement) IfFunc(f func(*Group)) *Statement
- func (s *Statement) Imag(c Code) *Statement
- func (s *Statement) Index(items ...Code) *Statement
- func (s *Statement) IndexFunc(f func(*Group)) *Statement
- func (s *Statement) Int() *Statement
- func (s *Statement) Int16() *Statement
- func (s *Statement) Int32() *Statement
- func (s *Statement) Int64() *Statement
- func (s *Statement) Int8() *Statement
- func (s *Statement) Interface(methods ...Code) *Statement
- func (s *Statement) InterfaceFunc(f func(*Group)) *Statement
- func (s *Statement) Iota() *Statement
- func (s *Statement) Len(v Code) *Statement
- func (s *Statement) Line() *Statement
- func (s *Statement) List(items ...Code) *Statement
- func (s *Statement) ListFunc(f func(*Group)) *Statement
- func (s *Statement) Lit(v interface{}) *Statement
- func (s *Statement) LitByte(v byte) *Statement
- func (s *Statement) LitByteFunc(f func() byte) *Statement
- func (s *Statement) LitFunc(f func() interface{}) *Statement
- func (s *Statement) LitRune(v rune) *Statement
- func (s *Statement) LitRuneFunc(f func() rune) *Statement
- func (s *Statement) Make(args ...Code) *Statement
- func (s *Statement) Map(typ Code) *Statement
- func (s *Statement) New(typ Code) *Statement
- func (s *Statement) Nil() *Statement
- func (s *Statement) Null() *Statement
- func (s *Statement) Op(op string) *Statement
- func (s *Statement) Panic(v Code) *Statement
- func (s *Statement) Params(params ...Code) *Statement
- func (s *Statement) ParamsFunc(f func(*Group)) *Statement
- func (s *Statement) Parens(item Code) *Statement
- func (s *Statement) Print(args ...Code) *Statement
- func (s *Statement) PrintFunc(f func(*Group)) *Statement
- func (s *Statement) Println(args ...Code) *Statement
- func (s *Statement) PrintlnFunc(f func(*Group)) *Statement
- func (s *Statement) Qual(path, name string) *Statement
- func (s *Statement) Range() *Statement
- func (s *Statement) Real(c Code) *Statement
- func (s *Statement) Recover() *Statement
- func (s *Statement) Render(writer io.Writer) error
- func (s *Statement) RenderWithFile(writer io.Writer, file *File) error
- func (s *Statement) Return(results ...Code) *Statement
- func (s *Statement) ReturnFunc(f func(*Group)) *Statement
- func (s *Statement) Rune() *Statement
- func (s *Statement) Select() *Statement
- func (s *Statement) String() *Statement
- func (s *Statement) Struct(fields ...Code) *Statement
- func (s *Statement) StructFunc(f func(*Group)) *Statement
- func (s *Statement) Switch(conditions ...Code) *Statement
- func (s *Statement) SwitchFunc(f func(*Group)) *Statement
- func (s *Statement) Tag(items map[string]string) *Statement
- func (s *Statement) True() *Statement
- func (s *Statement) Type() *Statement
- func (s *Statement) Uint() *Statement
- func (s *Statement) Uint16() *Statement
- func (s *Statement) Uint32() *Statement
- func (s *Statement) Uint64() *Statement
- func (s *Statement) Uint8() *Statement
- func (s *Statement) Uintptr() *Statement
- func (s *Statement) Values(values ...Code) *Statement
- func (s *Statement) ValuesFunc(f func(*Group)) *Statement
- func (s *Statement) Var() *Statement
Examples ¶
- Add
- Add (Var)
- Append
- Append (More)
- Assert
- Block
- Block (Case)
- Block (Complex)
- Block (If)
- BlockFunc
- BlockFunc (Case)
- Bool
- Break
- Byte
- Call
- Call (Fmt)
- CallFunc
- Cap
- Case
- CaseFunc
- Chan
- Close
- Comment
- Comment (Formatting_disabled)
- Comment (Multiline)
- Commentf
- Complex
- Complex128
- Complex64
- Custom
- CustomFunc
- Defer
- Defs
- Dict
- Dict (Nil)
- DictFunc
- Do
- Dot
- Empty
- Err
- File.Anon
- File.CgoPreamble
- File.CgoPreamble (Anon)
- File.CgoPreamble (No_preamble)
- File.CgoPreamble (No_preamble_anon)
- File.CgoPreamble (No_preamble_single)
- File.CgoPreamble (No_preamble_single_anon)
- File.ImportAlias
- File.ImportAlias (Conflict)
- File.ImportName
- File.ImportName (Conflict)
- File.ImportNames
- File.Render
- For
- Func (Declaration)
- Func (Literal)
- Goto
- Id
- Id (Local)
- Id (Remote)
- Id (Select)
- If
- Index
- Index (Empty)
- Index (Index)
- Interface
- Interface (Empty)
- List
- Lit
- Lit (Bool_false)
- Lit (Bool_true)
- Lit (Byte)
- Lit (Complex128)
- Lit (Complex64)
- Lit (Float)
- Lit (Float32)
- Lit (Float64_negative)
- Lit (Float64_negative_whole)
- Lit (Float64_one_point_zero)
- Lit (Float64_zero)
- Lit (Int)
- Lit (Int16)
- Lit (Int32)
- Lit (Int64)
- Lit (Int8)
- Lit (Rune)
- Lit (String)
- Lit (Uint)
- Lit (Uint16)
- Lit (Uint32)
- Lit (Uint64)
- Lit (Uint8)
- Lit (Uintptr)
- LitByte
- LitByteFunc
- LitFunc
- LitRune
- LitRuneFunc
- Map
- NewFile
- NewFilePath
- NewFilePathName
- Null (And_nil)
- Null (Index)
- Op
- Op (Complex_conditions)
- Op (Star)
- Op (Variadic)
- Params
- Parens
- Parens (Order)
- Qual
- Qual (File)
- Qual (Local)
- Return
- Statement.Clone (Broken)
- Statement.Clone (Fixed)
- Struct
- Struct (Empty)
- Switch
- Tag
- Values
- Values (Dict_composite)
- Values (Dict_multiple)
- Values (Dict_single)
- ValuesFunc
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func IsReservedWord ¶ added in v1.4.0
IsReservedWord returns if this is a reserved word in go
Types ¶
type Code ¶
type Code interface {
// contains filtered or unexported methods
}
Code represents an item of code that can be rendered.
type Dict ¶
Dict renders as key/value pairs. Use with Values for map or composite literals.
Example ¶
c := Id("a").Op(":=").Map(String()).String().Values(Dict{ Lit("a"): Lit("b"), Lit("c"): Lit("d"), }) fmt.Printf("%#v", c)
Output: a := map[string]string{ "a": "b", "c": "d", }
Example (Nil) ¶
c := Id("a").Op(":=").Map(String()).String().Values() fmt.Printf("%#v", c)
Output: a := map[string]string{}
func DictFunc ¶
DictFunc executes a func(Dict) to generate the value. Use with Values for map or composite literals.
Example ¶
c := Id("a").Op(":=").Map(String()).String().Values(DictFunc(func(d Dict) { d[Lit("a")] = Lit("b") d[Lit("c")] = Lit("d") })) fmt.Printf("%#v", c)
Output: a := map[string]string{ "a": "b", "c": "d", }
type File ¶
type File struct { *Group // If you're worried about generated package aliases conflicting with local variable names, you // can set a prefix here. Package foo becomes {prefix}_foo. PackagePrefix string // CanonicalPath adds a canonical import path annotation to the package clause. CanonicalPath string // contains filtered or unexported fields }
File represents a single source file. Package imports are managed automaticaly by File.
func NewFile ¶
NewFile Creates a new file, with the specified package name.
Example ¶
f := NewFile("main") f.Func().Id("main").Params().Block( Qual("fmt", "Println").Call(Lit("Hello, world")), ) fmt.Printf("%#v", f)
Output: package main import "fmt" func main() { fmt.Println("Hello, world") }
func NewFilePath ¶
NewFilePath creates a new file while specifying the package path - the package name is inferred from the path.
Example ¶
f := NewFilePath("a.b/c") f.Func().Id("init").Params().Block( Qual("a.b/c", "Foo").Call().Comment("Local package - alias is omitted."), Qual("d.e/f", "Bar").Call().Comment("Import is automatically added."), Qual("g.h/f", "Baz").Call().Comment("Colliding package name is automatically renamed."), ) fmt.Printf("%#v", f)
Output: package c import ( f "d.e/f" f1 "g.h/f" ) func init() { Foo() // Local package - alias is omitted. f.Bar() // Import is automatically added. f1.Baz() // Colliding package name is automatically renamed. }
func NewFilePathName ¶
NewFilePathName creates a new file with the specified package path and name.
Example ¶
f := NewFilePathName("a.b/c", "main") f.Func().Id("main").Params().Block( Qual("a.b/c", "Foo").Call(), ) fmt.Printf("%#v", f)
Output: package main func main() { Foo() }
func (*File) Anon ¶
Anon adds an anonymous import.
Example ¶
f := NewFile("c") f.Anon("a") f.Func().Id("init").Params().Block() fmt.Printf("%#v", f)
Output: package c import _ "a" func init() {}
func (*File) CgoPreamble ¶ added in v0.17.0
CgoPreamble adds a cgo preamble comment that is rendered directly before the "C" pseudo-package import.
Example ¶
f := NewFile("a") f.CgoPreamble(`#include <stdio.h> #include <stdlib.h> void myprint(char* s) { printf("%s\n", s); } `) f.Func().Id("init").Params().Block( Id("cs").Op(":=").Qual("C", "CString").Call(Lit("Hello from stdio\n")), Qual("C", "myprint").Call(Id("cs")), Qual("C", "free").Call(Qual("unsafe", "Pointer").Parens(Id("cs"))), ) fmt.Printf("%#v", f)
Output: package a import "unsafe" /* #include <stdio.h> #include <stdlib.h> void myprint(char* s) { printf("%s\n", s); } */ import "C" func init() { cs := C.CString("Hello from stdio\n") C.myprint(cs) C.free(unsafe.Pointer(cs)) }
Example (Anon) ¶
f := NewFile("a") f.CgoPreamble(`#include <stdio.h>`) f.Func().Id("init").Params().Block( Qual("foo.bar/a", "A"), Qual("foo.bar/b", "B"), ) fmt.Printf("%#v", f)
Output: package a import ( a "foo.bar/a" b "foo.bar/b" ) // #include <stdio.h> import "C" func init() { a.A b.B }
Example (No_preamble) ¶
f := NewFile("a") f.Func().Id("init").Params().Block( Qual("C", "Foo").Call(), Qual("fmt", "Print").Call(), ) fmt.Printf("%#v", f)
Output: package a import ( "C" "fmt" ) func init() { C.Foo() fmt.Print() }
Example (No_preamble_anon) ¶
f := NewFile("a") f.Anon("C") f.Func().Id("init").Params().Block( Qual("fmt", "Print").Call(), ) fmt.Printf("%#v", f)
Output: package a import ( "C" "fmt" ) func init() { fmt.Print() }
Example (No_preamble_single) ¶
f := NewFile("a") f.Func().Id("init").Params().Block( Qual("C", "Foo").Call(), ) fmt.Printf("%#v", f)
Output: package a import "C" func init() { C.Foo() }
Example (No_preamble_single_anon) ¶
f := NewFile("a") f.Anon("C") f.Func().Id("init").Params().Block() fmt.Printf("%#v", f)
Output: package a import "C" func init() {}
func (*File) HeaderComment ¶ added in v0.15.0
HeaderComment adds a comment to the top of the file, above any package comments. A blank line is rendered below the header comments, ensuring header comments are not included in the package doc.
func (*File) ImportAlias ¶ added in v0.18.0
ImportAlias provides the alias for a package path that should be used in the import block. A period can be used to force a dot-import.
Example ¶
f := NewFile("main") // package a should be aliased to "b" f.ImportAlias("github.com/foo/a", "b") // package c is not used in the code so will not be included f.ImportAlias("github.com/foo/c", "c") f.Func().Id("main").Params().Block( Qual("github.com/foo/a", "A").Call(), ) fmt.Printf("%#v", f)
Output: package main import b "github.com/foo/a" func main() { b.A() }
Example (Conflict) ¶
f := NewFile("main") // We provide a hint that package foo/a should use alias "b", but because package bar/b already // registers the required name, foo/a is aliased using the requested alias as a base. f.ImportName("github.com/foo/a", "b") f.Func().Id("main").Params().Block( Qual("github.com/bar/b", "Bar").Call(), Qual("github.com/foo/a", "Foo").Call(), ) fmt.Printf("%#v", f)
Output: package main import ( b "github.com/bar/b" b1 "github.com/foo/a" ) func main() { b.Bar() b1.Foo() }
func (*File) ImportName ¶ added in v0.18.0
ImportName provides the package name for a path. If specified, the alias will be omitted from the import block. This is optional. If not specified, a sensible package name is used based on the path and this is added as an alias in the import block.
Example ¶
f := NewFile("main") // package a should use name "a" f.ImportName("github.com/foo/a", "a") // package b is not used in the code so will not be included f.ImportName("github.com/foo/b", "b") f.Func().Id("main").Params().Block( Qual("github.com/foo/a", "A").Call(), ) fmt.Printf("%#v", f)
Output: package main import "github.com/foo/a" func main() { a.A() }
Example (Conflict) ¶
f := NewFile("main") // We provide a hint that package foo/a should use name "a", but because package bar/a already // registers the required name, foo/a is aliased. f.ImportName("github.com/foo/a", "a") f.Func().Id("main").Params().Block( Qual("github.com/bar/a", "Bar").Call(), Qual("github.com/foo/a", "Foo").Call(), ) fmt.Printf("%#v", f)
Output: package main import ( a "github.com/bar/a" a1 "github.com/foo/a" ) func main() { a.Bar() a1.Foo() }
func (*File) ImportNames ¶ added in v0.18.0
ImportNames allows multiple names to be imported as a map. Use the [gennames](gennames) command to automatically generate a go file containing a map of a selection of package names.
Example ¶
// package a should use name "a", package b is not used in the code so will not be included names := map[string]string{ "github.com/foo/a": "a", "github.com/foo/b": "b", } f := NewFile("main") f.ImportNames(names) f.Func().Id("main").Params().Block( Qual("github.com/foo/a", "A").Call(), ) fmt.Printf("%#v", f)
Output: package main import "github.com/foo/a" func main() { a.A() }
func (*File) PackageComment ¶
PackageComment adds a comment to the top of the file, above the package keyword.
type Group ¶
type Group struct {
// contains filtered or unexported fields
}
Group represents a list of Code items, separated by tokens with an optional open and close token.
func (*Group) AppendFunc ¶ added in v0.9.1
AppendFunc renders the append built-in function.
func (*Group) Assert ¶
Assert renders a period followed by a single item enclosed by parenthesis. Use for type assertions.
func (*Group) Block ¶
Block renders a statement list enclosed by curly braces. Use for code blocks. A special case applies when used directly after Case or Default, where the braces are omitted. This allows use in switch and select statements.
func (*Group) BlockFunc ¶
BlockFunc renders a statement list enclosed by curly braces. Use for code blocks. A special case applies when used directly after Case or Default, where the braces are omitted. This allows use in switch and select statements.
func (*Group) Call ¶
Call renders a comma separated list enclosed by parenthesis. Use for function calls.
func (*Group) CallFunc ¶
CallFunc renders a comma separated list enclosed by parenthesis. Use for function calls.
func (*Group) Comment ¶
Comment adds a comment. If the provided string contains a newline, the comment is formatted in multiline style. If the comment string starts with "//" or "/*", the automatic formatting is disabled and the string is rendered directly.
func (*Group) Commentf ¶
Commentf adds a comment, using a format string and a list of parameters. If the provided string contains a newline, the comment is formatted in multiline style. If the comment string starts with "//" or "/*", the automatic formatting is disabled and the string is rendered directly.
func (*Group) Complex128 ¶
Complex128 renders the complex128 identifier.
func (*Group) Custom ¶ added in v0.19.0
Custom renders a customized statement list. Pass in options to specify multi-line, and tokens for open, close, separator.
func (*Group) CustomFunc ¶ added in v0.19.0
CustomFunc renders a customized statement list. Pass in options to specify multi-line, and tokens for open, close, separator.
func (*Group) Defs ¶
Defs renders a statement list enclosed in parenthesis. Use for definition lists.
func (*Group) DefsFunc ¶
DefsFunc renders a statement list enclosed in parenthesis. Use for definition lists.
func (*Group) Do ¶
Do calls the provided function with the statement as a parameter. Use for embedding logic.
func (*Group) Dot ¶ added in v0.11.0
Dot renders a period followed by an identifier. Use for fields and selectors.
func (*Group) Empty ¶
Empty adds an empty item. Empty items render nothing but are followed by a separator in lists.
func (*Group) Fallthrough ¶
Fallthrough renders the fallthrough keyword.
func (*Group) Index ¶
Index renders a colon separated list enclosed by square brackets. Use for array / slice indexes and definitions.
func (*Group) IndexFunc ¶
IndexFunc renders a colon separated list enclosed by square brackets. Use for array / slice indexes and definitions.
func (*Group) Interface ¶
Interface renders the keyword followed by a method list enclosed by curly braces.
func (*Group) InterfaceFunc ¶
InterfaceFunc renders the keyword followed by a method list enclosed by curly braces.
func (*Group) ListFunc ¶
ListFunc renders a comma separated list. Use for multiple return functions.
func (*Group) Lit ¶
Lit renders a literal. Lit supports only built-in types (bool, string, int, complex128, float64, float32, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, uintptr and complex64). Passing any other type will panic.
func (*Group) LitByteFunc ¶ added in v0.13.0
LitByteFunc renders a byte literal. LitByteFunc generates the value to render by executing the provided function.
func (*Group) LitFunc ¶
LitFunc renders a literal. LitFunc generates the value to render by executing the provided function. LitFunc supports only built-in types (bool, string, int, complex128, float64, float32, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, uintptr and complex64). Returning any other type will panic.
func (*Group) LitRuneFunc ¶ added in v0.13.0
LitRuneFunc renders a rune literal. LitRuneFunc generates the value to render by executing the provided function.
func (*Group) Make ¶
Make renders the make built-in function. The final parameter of the make function is optional, so it is represented by a variadic parameter list.
func (*Group) Map ¶
Map renders the keyword followed by a single item enclosed by square brackets. Use for map definitions.
func (*Group) Null ¶
Null adds a null item. Null items render nothing and are not followed by a separator in lists.
func (*Group) Params ¶
Params renders a comma separated list enclosed by parenthesis. Use for function parameters and method receivers.
func (*Group) ParamsFunc ¶
ParamsFunc renders a comma separated list enclosed by parenthesis. Use for function parameters and method receivers.
func (*Group) Parens ¶
Parens renders a single item in parenthesis. Use for type conversion or to specify evaluation order.
func (*Group) PrintlnFunc ¶ added in v0.9.1
PrintlnFunc renders the println built-in function.
func (*Group) Qual ¶
Qual renders a qualified identifier. Imports are automatically added when used with a File. If the path matches the local path, the package name is omitted. If package names conflict they are automatically renamed. Note that it is not possible to reliably determine the package name given an arbitrary package path, so a sensible name is guessed from the path and added as an alias. The names of all standard library packages are known so these do not need to be aliased. If more control is needed of the aliases, see File.ImportName(#importname) or File.ImportAlias(#importalias).
func (*Group) RenderWithFile ¶ added in v1.3.0
RenderWithFile renders the Group to the provided writer, using imports from the provided file.
func (*Group) ReturnFunc ¶
ReturnFunc renders the keyword followed by a comma separated list.
func (*Group) Struct ¶
Struct renders the keyword followed by a field list enclosed by curly braces.
func (*Group) StructFunc ¶ added in v0.9.3
StructFunc renders the keyword followed by a field list enclosed by curly braces.
func (*Group) SwitchFunc ¶
SwitchFunc renders the keyword followed by a semicolon separated list.
func (*Group) Values ¶
Values renders a comma separated list enclosed by curly braces. Use for slice or composite literals.
func (*Group) ValuesFunc ¶
ValuesFunc renders a comma separated list enclosed by curly braces. Use for slice or composite literals.
type Statement ¶
type Statement []Code
Statement represents a simple list of code items. When rendered the items are separated by spaces.
func Add ¶
Add appends the provided items to the statement.
Example ¶
ptr := Op("*") c := Id("a").Op("=").Add(ptr).Id("b") fmt.Printf("%#v", c)
Output: a = *b
Example (Var) ¶
a := Id("a") i := Int() c := Var().Add(a, i) fmt.Printf("%#v", c)
Output: var a int
func Append ¶
Append renders the append built-in function.
Example ¶
c := Append(Id("a"), Id("b")) fmt.Printf("%#v", c)
Output: append(a, b)
Example (More) ¶
c := Id("a").Op("=").Append(Id("a"), Id("b").Op("...")) fmt.Printf("%#v", c)
Output: a = append(a, b...)
func AppendFunc ¶ added in v0.9.1
AppendFunc renders the append built-in function.
func Assert ¶
Assert renders a period followed by a single item enclosed by parenthesis. Use for type assertions.
Example ¶
c := List(Id("b"), Id("ok")).Op(":=").Id("a").Assert(Bool()) fmt.Printf("%#v", c)
Output: b, ok := a.(bool)
func Block ¶
Block renders a statement list enclosed by curly braces. Use for code blocks. A special case applies when used directly after Case or Default, where the braces are omitted. This allows use in switch and select statements.
Example ¶
c := Func().Id("foo").Params().String().Block( Id("a").Op("=").Id("b"), Id("b").Op("++"), Return(Id("b")), ) fmt.Printf("%#v", c)
Output: func foo() string { a = b b++ return b }
Example (Case) ¶
c := Select().Block( Case(Op("<-").Id("done")).Block( Return(Nil()), ), Case(List(Err(), Id("open")).Op(":=").Op("<-").Id("fail")).Block( If(Op("!").Id("open")).Block( Return(Err()), ), ), ) fmt.Printf("%#v", c)
Output: select { case <-done: return nil case err, open := <-fail: if !open { return err } }
Example (Complex) ¶
collection := func(name string, key Code, value Code) *Statement { if key == nil { // slice return Var().Id(name).Index().Add(value) } else { // map return Var().Id(name).Map(key).Add(value) } } c := Func().Id("main").Params().Block( collection("foo", nil, String()), collection("bar", String(), Int()), ) fmt.Printf("%#v", c)
Output: func main() { var foo []string var bar map[string]int }
Example (If) ¶
c := If(Id("a").Op(">").Lit(10)).Block( Id("a").Op("=").Id("a").Op("/").Lit(2), ) fmt.Printf("%#v", c)
Output: if a > 10 { a = a / 2 }
func BlockFunc ¶
BlockFunc renders a statement list enclosed by curly braces. Use for code blocks. A special case applies when used directly after Case or Default, where the braces are omitted. This allows use in switch and select statements.
Example ¶
increment := true name := "a" c := Func().Id("a").Params().BlockFunc(func(g *Group) { g.Id(name).Op("=").Lit(1) if increment { g.Id(name).Op("++") } else { g.Id(name).Op("--") } }) fmt.Printf("%#v", c)
Output: func a() { a = 1 a++ }
Example (Case) ¶
preventExitOnError := true c := Select().Block( Case(Op("<-").Id("done")).Block( Return(Nil()), ), Case(Err().Op(":=").Op("<-").Id("fail")).BlockFunc(func(g *Group) { if !preventExitOnError { g.Return(Err()) } else { g.Qual("fmt", "Println").Call(Err()) } }), ) fmt.Printf("%#v", c)
Output: select { case <-done: return nil case err := <-fail: fmt.Println(err) }
func Bool ¶
func Bool() *Statement
Bool renders the bool identifier.
Example ¶
c := Var().Id("b").Bool() fmt.Printf("%#v", c)
Output: var b bool
func Break ¶
func Break() *Statement
Break renders the break keyword.
Example ¶
c := For( Id("i").Op(":=").Lit(0), Id("i").Op("<").Lit(10), Id("i").Op("++"), ).Block( If(Id("i").Op(">").Lit(5)).Block( Break(), ), ) fmt.Printf("%#v", c)
Output: for i := 0; i < 10; i++ { if i > 5 { break } }
func Byte ¶
func Byte() *Statement
Byte renders the byte identifier.
Example ¶
c := Id("b").Op(":=").Id("a").Assert(Byte()) fmt.Printf("%#v", c)
Output: b := a.(byte)
func Call ¶
Call renders a comma separated list enclosed by parenthesis. Use for function calls.
Example ¶
c := Qual("fmt", "Printf").Call( Lit("%#v: %T\n"), Id("a"), Id("b"), ) fmt.Printf("%#v", c)
Output: fmt.Printf("%#v: %T\n", a, b)
Example (Fmt) ¶
c := Id("a").Call(Lit("b")) fmt.Printf("%#v", c)
Output: a("b")
func CallFunc ¶
CallFunc renders a comma separated list enclosed by parenthesis. Use for function calls.
Example ¶
f := func(name string, second string) { c := Id("foo").CallFunc(func(g *Group) { g.Id(name) if second != "" { g.Lit(second) } }) fmt.Printf("%#v\n", c) } f("a", "b") f("c", "")
Output: foo(a, "b") foo(c)
func Cap ¶
Cap renders the cap built-in function.
Example ¶
c := Id("i").Op(":=").Cap(Id("v")) fmt.Printf("%#v", c)
Output: i := cap(v)
func Case ¶
Case renders the keyword followed by a comma separated list.
Example ¶
c := Switch(Id("person")).Block( Case(Id("John"), Id("Peter")).Block( Return(Lit("male")), ), Case(Id("Gill")).Block( Return(Lit("female")), ), ) fmt.Printf("%#v", c)
Output: switch person { case John, Peter: return "male" case Gill: return "female" }
func CaseFunc ¶
CaseFunc renders the keyword followed by a comma separated list.
Example ¶
samIsMale := false c := Switch(Id("person")).Block( CaseFunc(func(g *Group) { g.Id("John") g.Id("Peter") if samIsMale { g.Id("Sam") } }).Block( Return(Lit("male")), ), CaseFunc(func(g *Group) { g.Id("Gill") if !samIsMale { g.Id("Sam") } }).Block( Return(Lit("female")), ), ) fmt.Printf("%#v", c)
Output: switch person { case John, Peter: return "male" case Gill, Sam: return "female" }
func Chan ¶
func Chan() *Statement
Chan renders the chan keyword.
Example ¶
c := Func().Id("init").Params().Block( Id("c").Op(":=").Make(Chan().Qual("os", "Signal"), Lit(1)), Qual("os/signal", "Notify").Call(Id("c"), Qual("os", "Interrupt")), Qual("os/signal", "Notify").Call(Id("c"), Qual("syscall", "SIGTERM")), Go().Func().Params().Block( Op("<-").Id("c"), Id("cancel").Call(), ).Call(), ) fmt.Printf("%#v", c)
Output: func init() { c := make(chan os.Signal, 1) signal.Notify(c, os.Interrupt) signal.Notify(c, syscall.SIGTERM) go func() { <-c cancel() }() }
func Close ¶
Close renders the close built-in function.
Example ¶
c := Block( Id("ch").Op(":=").Make(Chan().Struct()), Go().Func().Params().Block( Op("<-").Id("ch"), Qual("fmt", "Println").Call(Lit("done.")), ).Call(), Close(Id("ch")), ) fmt.Printf("%#v", c)
Output: { ch := make(chan struct{}) go func() { <-ch fmt.Println("done.") }() close(ch) }
func Comment ¶
Comment adds a comment. If the provided string contains a newline, the comment is formatted in multiline style. If the comment string starts with "//" or "/*", the automatic formatting is disabled and the string is rendered directly.
Example ¶
f := NewFile("a") f.Comment("Foo returns the string \"foo\"") f.Func().Id("Foo").Params().String().Block( Return(Lit("foo")).Comment("return the string foo"), ) fmt.Printf("%#v", f)
Output: package a // Foo returns the string "foo" func Foo() string { return "foo" // return the string foo }
Example (Formatting_disabled) ¶
c := Id("foo").Call(Comment("/* inline */")).Comment("//no-space") fmt.Printf("%#v", c)
Output: foo( /* inline */ ) //no-space
Example (Multiline) ¶
c := Comment("a\nb") fmt.Printf("%#v", c)
Output: /* a b */
func Commentf ¶
Commentf adds a comment, using a format string and a list of parameters. If the provided string contains a newline, the comment is formatted in multiline style. If the comment string starts with "//" or "/*", the automatic formatting is disabled and the string is rendered directly.
Example ¶
name := "foo" val := "bar" c := Id(name).Op(":=").Lit(val).Commentf("%s is the string \"%s\"", name, val) fmt.Printf("%#v", c)
Output: foo := "bar" // foo is the string "bar"
func Complex ¶
Complex renders the complex built-in function.
Example ¶
c := Func().Id("main").Params().Block( Id("c1").Op(":=").Lit(1+3.75i), Id("c2").Op(":=").Complex(Lit(1), Lit(3.75)), Qual("fmt", "Println").Call(Id("c1").Op("==").Id("c2")), ) fmt.Printf("%#v", c)
Output: func main() { c1 := (1 + 3.75i) c2 := complex(1, 3.75) fmt.Println(c1 == c2) }
func Complex128 ¶
func Complex128() *Statement
Complex128 renders the complex128 identifier.
Example ¶
c := Func().Id("main").Params().Block( Var().Id("c").Complex128(), Id("c").Op("=").Lit(1+2i), Qual("fmt", "Println").Call(Id("c")), ) fmt.Printf("%#v", c)
Output: func main() { var c complex128 c = (1 + 2i) fmt.Println(c) }
func Complex64 ¶
func Complex64() *Statement
Complex64 renders the complex64 identifier.
Example ¶
c := Func().Id("main").Params().Block( Var().Id("c64").Complex64(), Id("c64").Op("=").Complex(Lit(5), Float32().Parens(Lit(2))), Qual("fmt", "Printf").Call(Lit("%T\n"), Id("c64")), ) fmt.Printf("%#v", c)
Output: func main() { var c64 complex64 c64 = complex(5, float32(2)) fmt.Printf("%T\n", c64) }
func Custom ¶ added in v0.19.0
Custom renders a customized statement list. Pass in options to specify multi-line, and tokens for open, close, separator.
Example ¶
multiLineCall := Options{ Close: ")", Multi: true, Open: "(", Separator: ",", } c := Id("foo").Custom(multiLineCall, Lit("a"), Lit("b"), Lit("c")) fmt.Printf("%#v", c)
Output: foo( "a", "b", "c", )
func CustomFunc ¶ added in v0.19.0
CustomFunc renders a customized statement list. Pass in options to specify multi-line, and tokens for open, close, separator.
Example ¶
multiLineCall := Options{ Close: ")", Multi: true, Open: "(", Separator: ",", } c := Id("foo").CustomFunc(multiLineCall, func(g *Group) { g.Lit("a") g.Lit("b") g.Lit("c") }) fmt.Printf("%#v", c)
Output: foo( "a", "b", "c", )
func Defer ¶
func Defer() *Statement
Defer renders the defer keyword.
Example ¶
c := Defer().Id("foo").Call() fmt.Printf("%#v", c)
Output: defer foo()
func Defs ¶
Defs renders a statement list enclosed in parenthesis. Use for definition lists.
Example ¶
c := Const().Defs( Id("a").Op("=").Lit("a"), Id("b").Op("=").Lit("b"), ) fmt.Printf("%#v", c)
Output: const ( a = "a" b = "b" )
func DefsFunc ¶
DefsFunc renders a statement list enclosed in parenthesis. Use for definition lists.
func Do ¶
Do calls the provided function with the statement as a parameter. Use for embedding logic.
Example ¶
f := func(name string, isMap bool) *Statement { return Id(name).Op(":=").Do(func(s *Statement) { if isMap { s.Map(String()).String() } else { s.Index().String() } }).Values() } fmt.Printf("%#v\n%#v", f("a", true), f("b", false))
Output: a := map[string]string{} b := []string{}
func Dot ¶ added in v0.11.0
Dot renders a period followed by an identifier. Use for fields and selectors.
Example ¶
c := Qual("a.b/c", "Foo").Call().Dot("Bar").Index(Lit(0)).Dot("Baz") fmt.Printf("%#v", c)
Output: c.Foo().Bar[0].Baz
func Empty ¶
func Empty() *Statement
Empty adds an empty item. Empty items render nothing but are followed by a separator in lists.
Example ¶
c := Id("a").Op(":=").Id("b").Index(Lit(1), Empty()) fmt.Printf("%#v", c)
Output: a := b[1:]
func Err ¶
func Err() *Statement
Err renders the err identifier.
Example ¶
c := If( Err().Op(":=").Id("foo").Call(), Err().Op("!=").Nil(), ).Block( Return(Err()), ) fmt.Printf("%#v", c)
Output: if err := foo(); err != nil { return err }
func For ¶
For renders the keyword followed by a semicolon separated list.
Example ¶
c := For( Id("i").Op(":=").Lit(0), Id("i").Op("<").Lit(10), Id("i").Op("++"), ).Block( Qual("fmt", "Println").Call(Id("i")), ) fmt.Printf("%#v", c)
Output: for i := 0; i < 10; i++ { fmt.Println(i) }
func Func ¶
func Func() *Statement
Func renders the func keyword.
Example (Declaration) ¶
c := Func().Id("a").Params().Block() fmt.Printf("%#v", c)
Output: func a() {}
Example (Literal) ¶
c := Id("a").Op(":=").Func().Params().Block() fmt.Printf("%#v", c)
Output: a := func() {}
func Goto ¶
func Goto() *Statement
Goto renders the goto keyword.
Example ¶
c := Goto().Id("Outer") fmt.Printf("%#v", c)
Output: goto Outer
func Id ¶
Id renders an identifier.
Example ¶
c := If(Id("i").Op("==").Id("j")).Block( Return(Id("i")), ) fmt.Printf("%#v", c)
Output: if i == j { return i }
Example (Local) ¶
c := Id("a").Op(":=").Lit(1) fmt.Printf("%#v", c)
Output: a := 1
Example (Remote) ¶
f := NewFile("main") f.Func().Id("main").Params().Block( Qual("fmt", "Println").Call( Lit("Hello, world"), ), ) fmt.Printf("%#v", f)
Output: package main import "fmt" func main() { fmt.Println("Hello, world") }
Example (Select) ¶
c := Id("a").Dot("b").Dot("c").Call() fmt.Printf("%#v", c)
Output: a.b.c()
func If ¶
If renders the keyword followed by a semicolon separated list.
Example ¶
c := If( Err().Op(":=").Id("a").Call(), Err().Op("!=").Nil(), ).Block( Return(Err()), ) fmt.Printf("%#v", c)
Output: if err := a(); err != nil { return err }
func Index ¶
Index renders a colon separated list enclosed by square brackets. Use for array / slice indexes and definitions.
Example ¶
c := Var().Id("a").Index().String() fmt.Printf("%#v", c)
Output: var a []string
Example (Empty) ¶
c := Id("a").Op(":=").Id("b").Index(Lit(1), Empty()) fmt.Printf("%#v", c)
Output: a := b[1:]
Example (Index) ¶
c := Id("a").Op(":=").Id("b").Index(Lit(0), Lit(1)) fmt.Printf("%#v", c)
Output: a := b[0:1]
func IndexFunc ¶
IndexFunc renders a colon separated list enclosed by square brackets. Use for array / slice indexes and definitions.
func Interface ¶
Interface renders the keyword followed by a method list enclosed by curly braces.
Example ¶
c := Type().Id("a").Interface( Id("b").Params().String(), ) fmt.Printf("%#v", c)
Output: type a interface { b() string }
Example (Empty) ¶
c := Var().Id("a").Interface() fmt.Printf("%#v", c)
Output: var a interface{}
func InterfaceFunc ¶
InterfaceFunc renders the keyword followed by a method list enclosed by curly braces.
func List ¶
List renders a comma separated list. Use for multiple return functions.
Example ¶
c := List(Id("a"), Err()).Op(":=").Id("b").Call() fmt.Printf("%#v", c)
Output: a, err := b()
func Lit ¶
func Lit(v interface{}) *Statement
Lit renders a literal. Lit supports only built-in types (bool, string, int, complex128, float64, float32, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, uintptr and complex64). Passing any other type will panic.
Example ¶
c := Id("a").Op(":=").Lit("a") fmt.Printf("%#v", c)
Output: a := "a"
Example (Bool_false) ¶
c := Lit(false) fmt.Printf("%#v", c)
Output: false
Example (Bool_true) ¶
c := Lit(true) fmt.Printf("%#v", c)
Output: true
Example (Byte) ¶
// Lit can't tell the difference between byte and uint8. Use LitByte to // render byte literals. c := Lit(byte(0x1)) fmt.Printf("%#v", c)
Output: uint8(0x1)
Example (Complex128) ¶
c := Lit(0 + 0i) fmt.Printf("%#v", c)
Output: (0 + 0i)
Example (Complex64) ¶
c := Lit(complex64(0 + 0i)) fmt.Printf("%#v", c)
Output: complex64(0 + 0i)
Example (Float) ¶
c := Id("a").Op(":=").Lit(1.5) fmt.Printf("%#v", c)
Output: a := 1.5
Example (Float32) ¶
c := Lit(float32(1)) fmt.Printf("%#v", c)
Output: float32(1)
Example (Float64_negative) ¶
c := Lit(-0.1) fmt.Printf("%#v", c)
Output: -0.1
Example (Float64_negative_whole) ¶
c := Lit(-1.0) fmt.Printf("%#v", c)
Output: -1.0
Example (Float64_one_point_zero) ¶
c := Lit(1.0) fmt.Printf("%#v", c)
Output: 1.0
Example (Float64_zero) ¶
c := Lit(0.0) fmt.Printf("%#v", c)
Output: 0.0
Example (Int) ¶
c := Lit(1) fmt.Printf("%#v", c)
Output: 1
Example (Int16) ¶
c := Lit(int16(1)) fmt.Printf("%#v", c)
Output: int16(1)
Example (Int32) ¶
c := Lit(int32(1)) fmt.Printf("%#v", c)
Output: int32(1)
Example (Int64) ¶
c := Lit(int64(1)) fmt.Printf("%#v", c)
Output: int64(1)
Example (Int8) ¶
c := Lit(int8(1)) fmt.Printf("%#v", c)
Output: int8(1)
Example (Rune) ¶
// Lit can't tell the difference between rune and int32. Use LitRune to // render rune literals. c := Lit('x') fmt.Printf("%#v", c)
Output: int32(120)
Example (String) ¶
c := Lit("foo") fmt.Printf("%#v", c)
Output: "foo"
Example (Uint) ¶
c := Lit(uint(0x1)) fmt.Printf("%#v", c)
Output: uint(0x1)
Example (Uint16) ¶
c := Lit(uint16(0x1)) fmt.Printf("%#v", c)
Output: uint16(0x1)
Example (Uint32) ¶
c := Lit(uint32(0x1)) fmt.Printf("%#v", c)
Output: uint32(0x1)
Example (Uint64) ¶
c := Lit(uint64(0x1)) fmt.Printf("%#v", c)
Output: uint64(0x1)
Example (Uint8) ¶
c := Lit(uint8(0x1)) fmt.Printf("%#v", c)
Output: uint8(0x1)
Example (Uintptr) ¶
c := Lit(uintptr(0x1)) fmt.Printf("%#v", c)
Output: uintptr(0x1)
func LitByte ¶ added in v0.13.0
LitByte renders a byte literal.
Example ¶
c := LitByte(byte(1)) fmt.Printf("%#v", c)
Output: byte(0x1)
func LitByteFunc ¶ added in v0.13.0
LitByteFunc renders a byte literal. LitByteFunc generates the value to render by executing the provided function.
Example ¶
c := LitByteFunc(func() byte { return byte(2) }) fmt.Printf("%#v", c)
Output: byte(0x2)
func LitFunc ¶
func LitFunc(f func() interface{}) *Statement
LitFunc renders a literal. LitFunc generates the value to render by executing the provided function. LitFunc supports only built-in types (bool, string, int, complex128, float64, float32, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, uintptr and complex64). Returning any other type will panic.
Example ¶
c := Id("a").Op(":=").LitFunc(func() interface{} { return 1 + 1 }) fmt.Printf("%#v", c)
Output: a := 2
func LitRune ¶ added in v0.13.0
LitRune renders a rune literal.
Example ¶
c := LitRune('x') fmt.Printf("%#v", c)
Output: 'x'
func LitRuneFunc ¶ added in v0.13.0
LitRuneFunc renders a rune literal. LitRuneFunc generates the value to render by executing the provided function.
Example ¶
c := LitRuneFunc(func() rune { return '\t' }) fmt.Printf("%#v", c)
Output: '\t'
func Make ¶
Make renders the make built-in function. The final parameter of the make function is optional, so it is represented by a variadic parameter list.
func Map ¶
Map renders the keyword followed by a single item enclosed by square brackets. Use for map definitions.
Example ¶
c := Id("a").Op(":=").Map(String()).String().Values() fmt.Printf("%#v", c)
Output: a := map[string]string{}
func Null ¶
func Null() *Statement
Null adds a null item. Null items render nothing and are not followed by a separator in lists.
Example (And_nil) ¶
c := Func().Id("foo").Params( nil, Id("s").String(), Null(), Id("i").Int(), ).Block() fmt.Printf("%#v", c)
Output: func foo(s string, i int) {}
Example (Index) ¶
c := Id("a").Op(":=").Id("b").Index(Lit(1), Null()) fmt.Printf("%#v", c)
Output: a := b[1]
func Op ¶
Op renders the provided operator / token.
Example ¶
c := Id("a").Op(":=").Id("b").Call() fmt.Printf("%#v", c)
Output: a := b()
Example (Complex_conditions) ¶
c := If(Parens(Id("a").Op("||").Id("b")).Op("&&").Id("c")).Block() fmt.Printf("%#v", c)
Output: if (a || b) && c { }
Example (Star) ¶
c := Id("a").Op("=").Op("*").Id("b") fmt.Printf("%#v", c)
Output: a = *b
Example (Variadic) ¶
c := Id("a").Call(Id("b").Op("...")) fmt.Printf("%#v", c)
Output: a(b...)
func Params ¶
Params renders a comma separated list enclosed by parenthesis. Use for function parameters and method receivers.
Example ¶
c := Func().Params( Id("a").Id("A"), ).Id("foo").Params( Id("b"), Id("c").String(), ).String().Block( Return(Id("b").Op("+").Id("c")), ) fmt.Printf("%#v", c)
Output: func (a A) foo(b, c string) string { return b + c }
func ParamsFunc ¶
ParamsFunc renders a comma separated list enclosed by parenthesis. Use for function parameters and method receivers.
func Parens ¶
Parens renders a single item in parenthesis. Use for type conversion or to specify evaluation order.
Example ¶
c := Id("b").Op(":=").Index().Byte().Parens(Id("s")) fmt.Printf("%#v", c)
Output: b := []byte(s)
Example (Order) ¶
c := Id("a").Op("/").Parens(Id("b").Op("+").Id("c")) fmt.Printf("%#v", c)
Output: a / (b + c)
func PrintlnFunc ¶ added in v0.9.1
PrintlnFunc renders the println built-in function.
func Qual ¶
Qual renders a qualified identifier. Imports are automatically added when used with a File. If the path matches the local path, the package name is omitted. If package names conflict they are automatically renamed. Note that it is not possible to reliably determine the package name given an arbitrary package path, so a sensible name is guessed from the path and added as an alias. The names of all standard library packages are known so these do not need to be aliased. If more control is needed of the aliases, see File.ImportName(#importname) or File.ImportAlias(#importalias).
Example ¶
c := Qual("encoding/gob", "NewEncoder").Call() fmt.Printf("%#v", c)
Output: gob.NewEncoder()
Example (File) ¶
f := NewFilePath("a.b/c") f.Func().Id("init").Params().Block( Qual("a.b/c", "Foo").Call().Comment("Local package - name is omitted."), Qual("d.e/f", "Bar").Call().Comment("Import is automatically added."), Qual("g.h/f", "Baz").Call().Comment("Colliding package name is renamed."), ) fmt.Printf("%#v", f)
Output: package c import ( f "d.e/f" f1 "g.h/f" ) func init() { Foo() // Local package - name is omitted. f.Bar() // Import is automatically added. f1.Baz() // Colliding package name is renamed. }
Example (Local) ¶
f := NewFilePath("a.b/c") f.Func().Id("main").Params().Block( Qual("a.b/c", "D").Call(), ) fmt.Printf("%#v", f)
Output: package c func main() { D() }
func Return ¶
Return renders the keyword followed by a comma separated list.
Example ¶
c := Return(Id("a"), Id("b")) fmt.Printf("%#v", c)
Output: return a, b
func ReturnFunc ¶
ReturnFunc renders the keyword followed by a comma separated list.
func Struct ¶
Struct renders the keyword followed by a field list enclosed by curly braces.
Example ¶
c := Type().Id("foo").Struct( List(Id("x"), Id("y")).Int(), Id("u").Float32(), ) fmt.Printf("%#v", c)
Output: type foo struct { x, y int u float32 }
Example (Empty) ¶
c := Id("c").Op(":=").Make(Chan().Struct()) fmt.Printf("%#v", c)
Output: c := make(chan struct{})
func StructFunc ¶ added in v0.9.3
StructFunc renders the keyword followed by a field list enclosed by curly braces.
func Switch ¶
Switch renders the keyword followed by a semicolon separated list.
Example ¶
c := Switch(Id("value").Dot("Kind").Call()).Block( Case(Qual("reflect", "Float32"), Qual("reflect", "Float64")).Block( Return(Lit("float")), ), Case(Qual("reflect", "Bool")).Block( Return(Lit("bool")), ), Case(Qual("reflect", "Uintptr")).Block( Fallthrough(), ), Default().Block( Return(Lit("none")), ), ) fmt.Printf("%#v", c)
Output: switch value.Kind() { case reflect.Float32, reflect.Float64: return "float" case reflect.Bool: return "bool" case reflect.Uintptr: fallthrough default: return "none" }
func SwitchFunc ¶
SwitchFunc renders the keyword followed by a semicolon separated list.
func Tag ¶
Tag renders a struct tag
Example ¶
c := Type().Id("foo").Struct( Id("A").String().Tag(map[string]string{"json": "a"}), Id("B").Int().Tag(map[string]string{"json": "b", "bar": "baz"}), ) fmt.Printf("%#v", c)
Output: type foo struct { A string `json:"a"` B int `bar:"baz" json:"b"` }
func Values ¶
Values renders a comma separated list enclosed by curly braces. Use for slice or composite literals.
Example ¶
c := Index().String().Values(Lit("a"), Lit("b")) fmt.Printf("%#v", c)
Output: []string{"a", "b"}
Example (Dict_composite) ¶
c := Op("&").Id("Person").Values(Dict{ Id("Age"): Lit(1), Id("Name"): Lit("a"), }) fmt.Printf("%#v", c)
Output: &Person{ Age: 1, Name: "a", }
Example (Dict_multiple) ¶
c := Map(String()).String().Values(Dict{ Lit("a"): Lit("b"), Lit("c"): Lit("d"), }) fmt.Printf("%#v", c)
Output: map[string]string{ "a": "b", "c": "d", }
Example (Dict_single) ¶
c := Map(String()).String().Values(Dict{ Lit("a"): Lit("b"), }) fmt.Printf("%#v", c)
Output: map[string]string{"a": "b"}
func ValuesFunc ¶
ValuesFunc renders a comma separated list enclosed by curly braces. Use for slice or composite literals.
Example ¶
c := Id("numbers").Op(":=").Index().Int().ValuesFunc(func(g *Group) { for i := 0; i <= 5; i++ { g.Lit(i) } }) fmt.Printf("%#v", c)
Output: numbers := []int{0, 1, 2, 3, 4, 5}
func (*Statement) AppendFunc ¶ added in v0.9.1
AppendFunc renders the append built-in function.
func (*Statement) Assert ¶
Assert renders a period followed by a single item enclosed by parenthesis. Use for type assertions.
func (*Statement) Block ¶
Block renders a statement list enclosed by curly braces. Use for code blocks. A special case applies when used directly after Case or Default, where the braces are omitted. This allows use in switch and select statements.
func (*Statement) BlockFunc ¶
BlockFunc renders a statement list enclosed by curly braces. Use for code blocks. A special case applies when used directly after Case or Default, where the braces are omitted. This allows use in switch and select statements.
func (*Statement) Call ¶
Call renders a comma separated list enclosed by parenthesis. Use for function calls.
func (*Statement) CallFunc ¶
CallFunc renders a comma separated list enclosed by parenthesis. Use for function calls.
func (*Statement) Clone ¶
Clone makes a copy of the Statement, so further tokens can be appended without affecting the original.
Example (Broken) ¶
a := Id("a") c := Block( a.Call(), a.Call(), ) fmt.Printf("%#v", c)
Output: { a()() a()() }
Example (Fixed) ¶
a := Id("a") c := Block( a.Clone().Call(), a.Clone().Call(), ) fmt.Printf("%#v", c)
Output: { a() a() }
func (*Statement) Comment ¶
Comment adds a comment. If the provided string contains a newline, the comment is formatted in multiline style. If the comment string starts with "//" or "/*", the automatic formatting is disabled and the string is rendered directly.
func (*Statement) Commentf ¶
Commentf adds a comment, using a format string and a list of parameters. If the provided string contains a newline, the comment is formatted in multiline style. If the comment string starts with "//" or "/*", the automatic formatting is disabled and the string is rendered directly.
func (*Statement) Complex128 ¶
Complex128 renders the complex128 identifier.
func (*Statement) Custom ¶ added in v0.19.0
Custom renders a customized statement list. Pass in options to specify multi-line, and tokens for open, close, separator.
func (*Statement) CustomFunc ¶ added in v0.19.0
CustomFunc renders a customized statement list. Pass in options to specify multi-line, and tokens for open, close, separator.
func (*Statement) Defs ¶
Defs renders a statement list enclosed in parenthesis. Use for definition lists.
func (*Statement) DefsFunc ¶
DefsFunc renders a statement list enclosed in parenthesis. Use for definition lists.
func (*Statement) Do ¶
Do calls the provided function with the statement as a parameter. Use for embedding logic.
func (*Statement) Dot ¶ added in v0.11.0
Dot renders a period followed by an identifier. Use for fields and selectors.
func (*Statement) Empty ¶
Empty adds an empty item. Empty items render nothing but are followed by a separator in lists.
func (*Statement) Fallthrough ¶
Fallthrough renders the fallthrough keyword.
func (*Statement) GoString ¶
GoString renders the Statement for testing. Any error will cause a panic.
func (*Statement) Index ¶
Index renders a colon separated list enclosed by square brackets. Use for array / slice indexes and definitions.
func (*Statement) IndexFunc ¶
IndexFunc renders a colon separated list enclosed by square brackets. Use for array / slice indexes and definitions.
func (*Statement) Interface ¶
Interface renders the keyword followed by a method list enclosed by curly braces.
func (*Statement) InterfaceFunc ¶
InterfaceFunc renders the keyword followed by a method list enclosed by curly braces.
func (*Statement) ListFunc ¶
ListFunc renders a comma separated list. Use for multiple return functions.
func (*Statement) Lit ¶
Lit renders a literal. Lit supports only built-in types (bool, string, int, complex128, float64, float32, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, uintptr and complex64). Passing any other type will panic.
func (*Statement) LitByteFunc ¶ added in v0.13.0
LitByteFunc renders a byte literal. LitByteFunc generates the value to render by executing the provided function.
func (*Statement) LitFunc ¶
LitFunc renders a literal. LitFunc generates the value to render by executing the provided function. LitFunc supports only built-in types (bool, string, int, complex128, float64, float32, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, uintptr and complex64). Returning any other type will panic.
func (*Statement) LitRuneFunc ¶ added in v0.13.0
LitRuneFunc renders a rune literal. LitRuneFunc generates the value to render by executing the provided function.
func (*Statement) Make ¶
Make renders the make built-in function. The final parameter of the make function is optional, so it is represented by a variadic parameter list.
func (*Statement) Map ¶
Map renders the keyword followed by a single item enclosed by square brackets. Use for map definitions.
func (*Statement) Null ¶
Null adds a null item. Null items render nothing and are not followed by a separator in lists.
func (*Statement) Params ¶
Params renders a comma separated list enclosed by parenthesis. Use for function parameters and method receivers.
func (*Statement) ParamsFunc ¶
ParamsFunc renders a comma separated list enclosed by parenthesis. Use for function parameters and method receivers.
func (*Statement) Parens ¶
Parens renders a single item in parenthesis. Use for type conversion or to specify evaluation order.
func (*Statement) PrintlnFunc ¶ added in v0.9.1
PrintlnFunc renders the println built-in function.
func (*Statement) Qual ¶
Qual renders a qualified identifier. Imports are automatically added when used with a File. If the path matches the local path, the package name is omitted. If package names conflict they are automatically renamed. Note that it is not possible to reliably determine the package name given an arbitrary package path, so a sensible name is guessed from the path and added as an alias. The names of all standard library packages are known so these do not need to be aliased. If more control is needed of the aliases, see File.ImportName(#importname) or File.ImportAlias(#importalias).
func (*Statement) RenderWithFile ¶ added in v1.3.0
RenderWithFile renders the Statement to the provided writer, using imports from the provided file.
func (*Statement) ReturnFunc ¶
ReturnFunc renders the keyword followed by a comma separated list.
func (*Statement) Struct ¶
Struct renders the keyword followed by a field list enclosed by curly braces.
func (*Statement) StructFunc ¶ added in v0.9.3
StructFunc renders the keyword followed by a field list enclosed by curly braces.
func (*Statement) SwitchFunc ¶
SwitchFunc renders the keyword followed by a semicolon separated list.
func (*Statement) Values ¶
Values renders a comma separated list enclosed by curly braces. Use for slice or composite literals.
func (*Statement) ValuesFunc ¶
ValuesFunc renders a comma separated list enclosed by curly braces. Use for slice or composite literals.