jen

package
v0.17.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 10, 2018 License: MIT Imports: 9 Imported by: 0

Documentation

Overview

Package jen is a code generator for Go

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Code

type Code interface {
	// contains filtered or unexported methods
}

Code represents an item of code that can be rendered.

type Dict

type Dict map[Code]Code

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

func DictFunc(f func(Dict)) Dict

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 package aliases conflicting with local variable
	// names, you can set a prefix here. Package foo becomes {prefix}_foo.
	PackagePrefix string
	// contains filtered or unexported fields
}

File represents a single source file. Package imports are managed automaticaly by File.

func NewFile

func NewFile(packageName string) *File

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 "fmt"

func main() {
	fmt.Println("Hello, world")
}

func NewFilePath

func NewFilePath(packagePath string) *File

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

func NewFilePathName(packagePath, packageName string) *File

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

func (f *File) Anon(paths ...string)

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

func (f *File) CgoPreamble(comment string)

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 "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 "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 "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) GoString

func (f *File) GoString() string

GoString renders the File for testing. Any error will cause a panic.

func (*File) HeaderComment added in v0.15.0

func (f *File) HeaderComment(comment string)

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) PackageComment

func (f *File) PackageComment(comment string)

PackageComment adds a comment to the top of the file, above the package keyword.

func (*File) Render

func (f *File) Render(w io.Writer) error

Render renders the file to the provided writer.

Example
f := NewFile("a")
f.Func().Id("main").Params().Block()
buf := &bytes.Buffer{}
err := f.Render(buf)
if err != nil {
	fmt.Println(err.Error())
} else {
	fmt.Println(buf.String())
}
Output:

package a

func main() {}

func (*File) Save

func (f *File) Save(filename string) error

Save renders the file and saves to the filename provided.

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) Add

func (g *Group) Add(code ...Code) *Statement

Add appends the provided items to the statement.

func (*Group) Append

func (g *Group) Append(args ...Code) *Statement

Append renders the append built-in function.

func (*Group) AppendFunc added in v0.9.1

func (g *Group) AppendFunc(f func(*Group)) *Statement

AppendFunc renders the append built-in function.

func (*Group) Assert

func (g *Group) Assert(typ Code) *Statement

Assert renders a period followed by a single item enclosed by parenthesis. Use for type assertions.

func (*Group) Block

func (g *Group) Block(statements ...Code) *Statement

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

func (g *Group) BlockFunc(f func(*Group)) *Statement

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) Bool

func (g *Group) Bool() *Statement

Bool renders the bool identifier.

func (*Group) Break

func (g *Group) Break() *Statement

Break renders the break keyword.

func (*Group) Byte

func (g *Group) Byte() *Statement

Byte renders the byte identifier.

func (*Group) Call

func (g *Group) Call(params ...Code) *Statement

Call renders a comma separated list enclosed by parenthesis. Use for function calls.

func (*Group) CallFunc

func (g *Group) CallFunc(f func(*Group)) *Statement

CallFunc renders a comma separated list enclosed by parenthesis. Use for function calls.

func (*Group) Cap

func (g *Group) Cap(v Code) *Statement

Cap renders the cap built-in function.

func (*Group) Case

func (g *Group) Case(cases ...Code) *Statement

Case renders the keyword followed by a comma separated list.

func (*Group) CaseFunc

func (g *Group) CaseFunc(f func(*Group)) *Statement

CaseFunc renders the keyword followed by a comma separated list.

func (*Group) Chan

func (g *Group) Chan() *Statement

Chan renders the chan keyword.

func (*Group) Close

func (g *Group) Close(c Code) *Statement

Close renders the close built-in function.

func (*Group) Comment

func (g *Group) Comment(str string) *Statement

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

func (g *Group) Commentf(format string, a ...interface{}) *Statement

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) Complex

func (g *Group) Complex(r Code, i Code) *Statement

Complex renders the complex built-in function.

func (*Group) Complex128

func (g *Group) Complex128() *Statement

Complex128 renders the complex128 identifier.

func (*Group) Complex64

func (g *Group) Complex64() *Statement

Complex64 renders the complex64 identifier.

func (*Group) Const

func (g *Group) Const() *Statement

Const renders the const keyword.

func (*Group) Continue

func (g *Group) Continue() *Statement

Continue renders the continue keyword.

func (*Group) Copy

func (g *Group) Copy(dst Code, src Code) *Statement

Copy renders the copy built-in function.

func (*Group) Default

func (g *Group) Default() *Statement

Default renders the default keyword.

func (*Group) Defer

func (g *Group) Defer() *Statement

Defer renders the defer keyword.

func (*Group) Defs

func (g *Group) Defs(definitions ...Code) *Statement

Defs renders a statement list enclosed in parenthesis. Use for definition lists.

func (*Group) DefsFunc

func (g *Group) DefsFunc(f func(*Group)) *Statement

DefsFunc renders a statement list enclosed in parenthesis. Use for definition lists.

func (*Group) Delete

func (g *Group) Delete(m Code, key Code) *Statement

Delete renders the delete built-in function.

func (*Group) Do

func (g *Group) Do(f func(*Statement)) *Statement

Do calls the provided function with the statement as a parameter. Use for embedding logic.

func (*Group) Dot added in v0.11.0

func (g *Group) Dot(name string) *Statement

Dot renders a period followed by an identifier. Use for fields and selectors.

func (*Group) Else

func (g *Group) Else() *Statement

Else renders the else keyword.

func (*Group) Empty

func (g *Group) Empty() *Statement

Empty adds an empty item. Empty items render nothing but are followed by a separator in lists.

func (*Group) Err

func (g *Group) Err() *Statement

Err renders the err identifier.

func (*Group) Error

func (g *Group) Error() *Statement

Error renders the error identifier.

func (*Group) Fallthrough

func (g *Group) Fallthrough() *Statement

Fallthrough renders the fallthrough keyword.

func (*Group) False

func (g *Group) False() *Statement

False renders the false identifier.

func (*Group) Float32

func (g *Group) Float32() *Statement

Float32 renders the float32 identifier.

func (*Group) Float64

func (g *Group) Float64() *Statement

Float64 renders the float64 identifier.

func (*Group) For

func (g *Group) For(conditions ...Code) *Statement

For renders the keyword followed by a semicolon separated list.

func (*Group) ForFunc

func (g *Group) ForFunc(f func(*Group)) *Statement

ForFunc renders the keyword followed by a semicolon separated list.

func (*Group) Func

func (g *Group) Func() *Statement

Func renders the func keyword.

func (*Group) Go

func (g *Group) Go() *Statement

Go renders the go keyword.

func (*Group) GoString

func (g *Group) GoString() string

GoString renders the Group for testing. Any error will cause a panic.

func (*Group) Goto

func (g *Group) Goto() *Statement

Goto renders the goto keyword.

func (*Group) Id

func (g *Group) Id(name string) *Statement

Id renders an identifier.

func (*Group) If

func (g *Group) If(conditions ...Code) *Statement

If renders the keyword followed by a semicolon separated list.

func (*Group) IfFunc

func (g *Group) IfFunc(f func(*Group)) *Statement

IfFunc renders the keyword followed by a semicolon separated list.

func (*Group) Imag

func (g *Group) Imag(c Code) *Statement

Imag renders the imag built-in function.

func (*Group) Index

func (g *Group) Index(items ...Code) *Statement

Index renders a colon separated list enclosed by square brackets. Use for array / slice indexes and definitions.

func (*Group) IndexFunc

func (g *Group) IndexFunc(f func(*Group)) *Statement

IndexFunc renders a colon separated list enclosed by square brackets. Use for array / slice indexes and definitions.

func (*Group) Int

func (g *Group) Int() *Statement

Int renders the int identifier.

func (*Group) Int16

func (g *Group) Int16() *Statement

Int16 renders the int16 identifier.

func (*Group) Int32

func (g *Group) Int32() *Statement

Int32 renders the int32 identifier.

func (*Group) Int64

func (g *Group) Int64() *Statement

Int64 renders the int64 identifier.

func (*Group) Int8

func (g *Group) Int8() *Statement

Int8 renders the int8 identifier.

func (*Group) Interface

func (g *Group) Interface(methods ...Code) *Statement

Interface renders the keyword followed by a method list enclosed by curly braces.

func (*Group) InterfaceFunc

func (g *Group) InterfaceFunc(f func(*Group)) *Statement

InterfaceFunc renders the keyword followed by a method list enclosed by curly braces.

func (*Group) Iota

func (g *Group) Iota() *Statement

Iota renders the iota identifier.

func (*Group) Len

func (g *Group) Len(v Code) *Statement

Len renders the len built-in function.

func (*Group) Line

func (g *Group) Line() *Statement

Line inserts a blank line.

func (*Group) List

func (g *Group) List(items ...Code) *Statement

List renders a comma separated list. Use for multiple return functions.

func (*Group) ListFunc

func (g *Group) ListFunc(f func(*Group)) *Statement

ListFunc renders a comma separated list. Use for multiple return functions.

func (*Group) Lit

func (g *Group) Lit(v interface{}) *Statement

Lit renders a literal, using the format provided by the fmt package %#v verb.

func (*Group) LitByte added in v0.13.0

func (g *Group) LitByte(v byte) *Statement

LitByte renders a byte literal.

func (*Group) LitByteFunc added in v0.13.0

func (g *Group) LitByteFunc(f func() byte) *Statement

LitByteFunc renders a byte literal. LitByteFunc generates the value to render by executing the provided function.

func (*Group) LitFunc

func (g *Group) LitFunc(f func() interface{}) *Statement

LitFunc renders a literal, using the format provided by the fmt package %#v verb. LitFunc generates the value to render by executing the provided function.

func (*Group) LitRune added in v0.13.0

func (g *Group) LitRune(v rune) *Statement

LitRune renders a rune literal.

func (*Group) LitRuneFunc added in v0.13.0

func (g *Group) LitRuneFunc(f func() rune) *Statement

LitRuneFunc renders a rune literal. LitRuneFunc generates the value to render by executing the provided function.

func (*Group) Make

func (g *Group) Make(args ...Code) *Statement

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

func (g *Group) Map(typ Code) *Statement

Map renders the keyword followed by a single item enclosed by square brackets. Use for map definitions.

func (*Group) New

func (g *Group) New(typ Code) *Statement

New renders the new built-in function.

func (*Group) Nil

func (g *Group) Nil() *Statement

Nil renders the nil identifier.

func (*Group) Null

func (g *Group) Null() *Statement

Null adds a null item. Null items render nothing and are not followed by a separator in lists.

func (*Group) Op

func (g *Group) Op(op string) *Statement

Op renders the provided operator / token.

func (*Group) Panic

func (g *Group) Panic(v Code) *Statement

Panic renders the panic built-in function.

func (*Group) Params

func (g *Group) Params(params ...Code) *Statement

Params renders a comma separated list enclosed by parenthesis. Use for function parameters and method receivers.

func (*Group) ParamsFunc

func (g *Group) ParamsFunc(f func(*Group)) *Statement

ParamsFunc renders a comma separated list enclosed by parenthesis. Use for function parameters and method receivers.

func (*Group) Parens

func (g *Group) Parens(item Code) *Statement

Parens renders a single item in parenthesis. Use for type conversion or to specify evaluation order.

func (*Group) Print

func (g *Group) Print(args ...Code) *Statement

Print renders the print built-in function.

func (*Group) PrintFunc added in v0.9.1

func (g *Group) PrintFunc(f func(*Group)) *Statement

PrintFunc renders the print built-in function.

func (*Group) Println

func (g *Group) Println(args ...Code) *Statement

Println renders the println built-in function.

func (*Group) PrintlnFunc added in v0.9.1

func (g *Group) PrintlnFunc(f func(*Group)) *Statement

PrintlnFunc renders the println built-in function.

func (*Group) Qual

func (g *Group) Qual(path, name string) *Statement

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.

func (*Group) Range

func (g *Group) Range() *Statement

Range renders the range keyword.

func (*Group) Real

func (g *Group) Real(c Code) *Statement

Real renders the real built-in function.

func (*Group) Recover

func (g *Group) Recover() *Statement

Recover renders the recover built-in function.

func (*Group) Render added in v0.15.0

func (g *Group) Render(writer io.Writer) error

Render renders the Group to the provided writer.

func (*Group) Return

func (g *Group) Return(results ...Code) *Statement

Return renders the keyword followed by a comma separated list.

func (*Group) ReturnFunc

func (g *Group) ReturnFunc(f func(*Group)) *Statement

ReturnFunc renders the keyword followed by a comma separated list.

func (*Group) Rune

func (g *Group) Rune() *Statement

Rune renders the rune identifier.

func (*Group) Select

func (g *Group) Select() *Statement

Select renders the select keyword.

func (*Group) String

func (g *Group) String() *Statement

String renders the string identifier.

func (*Group) Struct

func (g *Group) Struct(fields ...Code) *Statement

Struct renders the keyword followed by a field list enclosed by curly braces.

func (*Group) StructFunc added in v0.9.3

func (g *Group) StructFunc(f func(*Group)) *Statement

StructFunc renders the keyword followed by a field list enclosed by curly braces.

func (*Group) Switch

func (g *Group) Switch(conditions ...Code) *Statement

Switch renders the keyword followed by a semicolon separated list.

func (*Group) SwitchFunc

func (g *Group) SwitchFunc(f func(*Group)) *Statement

SwitchFunc renders the keyword followed by a semicolon separated list.

func (*Group) Tag

func (g *Group) Tag(items map[string]string) *Statement

Tag renders a struct tag

func (*Group) True

func (g *Group) True() *Statement

True renders the true identifier.

func (*Group) Type

func (g *Group) Type() *Statement

Type renders the type keyword.

func (*Group) Uint

func (g *Group) Uint() *Statement

Uint renders the uint identifier.

func (*Group) Uint16

func (g *Group) Uint16() *Statement

Uint16 renders the uint16 identifier.

func (*Group) Uint32

func (g *Group) Uint32() *Statement

Uint32 renders the uint32 identifier.

func (*Group) Uint64

func (g *Group) Uint64() *Statement

Uint64 renders the uint64 identifier.

func (*Group) Uint8

func (g *Group) Uint8() *Statement

Uint8 renders the uint8 identifier.

func (*Group) Uintptr

func (g *Group) Uintptr() *Statement

Uintptr renders the uintptr identifier.

func (*Group) Values

func (g *Group) Values(values ...Code) *Statement

Values renders a comma separated list enclosed by curly braces. Use for slice or composite literals.

func (*Group) ValuesFunc

func (g *Group) ValuesFunc(f func(*Group)) *Statement

ValuesFunc renders a comma separated list enclosed by curly braces. Use for slice or composite literals.

func (*Group) Var

func (g *Group) Var() *Statement

Var renders the var keyword.

type Statement

type Statement []Code

Statement represents a simple list of code items. When rendered the items are separated by spaces.

func Add

func Add(code ...Code) *Statement

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

func Append(args ...Code) *Statement

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

func AppendFunc(f func(*Group)) *Statement

AppendFunc renders the append built-in function.

func Assert

func Assert(typ Code) *Statement

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

func Block(statements ...Code) *Statement

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

func BlockFunc(f func(*Group)) *Statement

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

func Call(params ...Code) *Statement

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

func CallFunc(f func(*Group)) *Statement

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

func Cap(v Code) *Statement

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

func Case(cases ...Code) *Statement

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

func CaseFunc(f func(*Group)) *Statement

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

func Close(c Code) *Statement

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

func Comment(str string) *Statement

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

func Commentf(format string, a ...interface{}) *Statement

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

func Complex(r Code, i Code) *Statement

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 Const

func Const() *Statement

Const renders the const keyword.

func Continue

func Continue() *Statement

Continue renders the continue keyword.

func Copy

func Copy(dst Code, src Code) *Statement

Copy renders the copy built-in function.

func Default

func Default() *Statement

Default renders the default keyword.

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

func Defs(definitions ...Code) *Statement

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

func DefsFunc(f func(*Group)) *Statement

DefsFunc renders a statement list enclosed in parenthesis. Use for definition lists.

func Delete

func Delete(m Code, key Code) *Statement

Delete renders the delete built-in function.

func Do

func Do(f func(*Statement)) *Statement

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

func Dot(name string) *Statement

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 Else

func Else() *Statement

Else renders the else keyword.

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 Error

func Error() *Statement

Error renders the error identifier.

func Fallthrough

func Fallthrough() *Statement

Fallthrough renders the fallthrough keyword.

func False

func False() *Statement

False renders the false identifier.

func Float32

func Float32() *Statement

Float32 renders the float32 identifier.

func Float64

func Float64() *Statement

Float64 renders the float64 identifier.

func For

func For(conditions ...Code) *Statement

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 ForFunc

func ForFunc(f func(*Group)) *Statement

ForFunc renders the keyword followed by a semicolon separated list.

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 Go

func Go() *Statement

Go renders the go keyword.

func Goto

func Goto() *Statement

Goto renders the goto keyword.

Example
c := Goto().Id("Outer")
fmt.Printf("%#v", c)
Output:

goto Outer

func Id

func Id(name string) *Statement

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 "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

func If(conditions ...Code) *Statement

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 IfFunc

func IfFunc(f func(*Group)) *Statement

IfFunc renders the keyword followed by a semicolon separated list.

func Imag

func Imag(c Code) *Statement

Imag renders the imag built-in function.

func Index

func Index(items ...Code) *Statement

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

func IndexFunc(f func(*Group)) *Statement

IndexFunc renders a colon separated list enclosed by square brackets. Use for array / slice indexes and definitions.

func Int

func Int() *Statement

Int renders the int identifier.

func Int16

func Int16() *Statement

Int16 renders the int16 identifier.

func Int32

func Int32() *Statement

Int32 renders the int32 identifier.

func Int64

func Int64() *Statement

Int64 renders the int64 identifier.

func Int8

func Int8() *Statement

Int8 renders the int8 identifier.

func Interface

func Interface(methods ...Code) *Statement

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

func InterfaceFunc(f func(*Group)) *Statement

InterfaceFunc renders the keyword followed by a method list enclosed by curly braces.

func Iota

func Iota() *Statement

Iota renders the iota identifier.

func Len

func Len(v Code) *Statement

Len renders the len built-in function.

func Line

func Line() *Statement

Line inserts a blank line.

func List

func List(items ...Code) *Statement

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 ListFunc

func ListFunc(f func(*Group)) *Statement

ListFunc renders a comma separated list. Use for multiple return functions.

func Lit

func Lit(v interface{}) *Statement

Lit renders a literal, using the format provided by the fmt package %#v verb.

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

func LitByte(v byte) *Statement

LitByte renders a byte literal.

Example
c := LitByte(byte(1))
fmt.Printf("%#v", c)
Output:

byte(0x1)

func LitByteFunc added in v0.13.0

func LitByteFunc(f func() byte) *Statement

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, using the format provided by the fmt package %#v verb. LitFunc generates the value to render by executing the provided function.

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

func LitRune(v rune) *Statement

LitRune renders a rune literal.

Example
c := LitRune('x')
fmt.Printf("%#v", c)
Output:

'x'

func LitRuneFunc added in v0.13.0

func LitRuneFunc(f func() rune) *Statement

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

func Make(args ...Code) *Statement

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

func Map(typ Code) *Statement

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 New

func New(typ Code) *Statement

New renders the new built-in function.

func Nil

func Nil() *Statement

Nil renders the nil identifier.

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

func Op(op string) *Statement

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(Params(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 Panic

func Panic(v Code) *Statement

Panic renders the panic built-in function.

func Params

func Params(params ...Code) *Statement

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

func ParamsFunc(f func(*Group)) *Statement

ParamsFunc renders a comma separated list enclosed by parenthesis. Use for function parameters and method receivers.

func Parens

func Parens(item Code) *Statement

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 Print

func Print(args ...Code) *Statement

Print renders the print built-in function.

func PrintFunc added in v0.9.1

func PrintFunc(f func(*Group)) *Statement

PrintFunc renders the print built-in function.

func Println

func Println(args ...Code) *Statement

Println renders the println built-in function.

func PrintlnFunc added in v0.9.1

func PrintlnFunc(f func(*Group)) *Statement

PrintlnFunc renders the println built-in function.

func Qual

func Qual(path, name string) *Statement

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.

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 Range

func Range() *Statement

Range renders the range keyword.

func Real

func Real(c Code) *Statement

Real renders the real built-in function.

func Recover

func Recover() *Statement

Recover renders the recover built-in function.

func Return

func Return(results ...Code) *Statement

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

func ReturnFunc(f func(*Group)) *Statement

ReturnFunc renders the keyword followed by a comma separated list.

func Rune

func Rune() *Statement

Rune renders the rune identifier.

func Select

func Select() *Statement

Select renders the select keyword.

func String

func String() *Statement

String renders the string identifier.

func Struct

func Struct(fields ...Code) *Statement

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

func StructFunc(f func(*Group)) *Statement

StructFunc renders the keyword followed by a field list enclosed by curly braces.

func Switch

func Switch(conditions ...Code) *Statement

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

func SwitchFunc(f func(*Group)) *Statement

SwitchFunc renders the keyword followed by a semicolon separated list.

func Tag

func Tag(items map[string]string) *Statement

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 True

func True() *Statement

True renders the true identifier.

func Type

func Type() *Statement

Type renders the type keyword.

func Uint

func Uint() *Statement

Uint renders the uint identifier.

func Uint16

func Uint16() *Statement

Uint16 renders the uint16 identifier.

func Uint32

func Uint32() *Statement

Uint32 renders the uint32 identifier.

func Uint64

func Uint64() *Statement

Uint64 renders the uint64 identifier.

func Uint8

func Uint8() *Statement

Uint8 renders the uint8 identifier.

func Uintptr

func Uintptr() *Statement

Uintptr renders the uintptr identifier.

func Values

func Values(values ...Code) *Statement

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

func ValuesFunc(f func(*Group)) *Statement

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 Var

func Var() *Statement

Var renders the var keyword.

func (*Statement) Add

func (s *Statement) Add(code ...Code) *Statement

Add appends the provided items to the statement.

func (*Statement) Append

func (s *Statement) Append(args ...Code) *Statement

Append renders the append built-in function.

func (*Statement) AppendFunc added in v0.9.1

func (s *Statement) AppendFunc(f func(*Group)) *Statement

AppendFunc renders the append built-in function.

func (*Statement) Assert

func (s *Statement) Assert(typ Code) *Statement

Assert renders a period followed by a single item enclosed by parenthesis. Use for type assertions.

func (*Statement) Block

func (s *Statement) Block(statements ...Code) *Statement

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

func (s *Statement) BlockFunc(f func(*Group)) *Statement

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) Bool

func (s *Statement) Bool() *Statement

Bool renders the bool identifier.

func (*Statement) Break

func (s *Statement) Break() *Statement

Break renders the break keyword.

func (*Statement) Byte

func (s *Statement) Byte() *Statement

Byte renders the byte identifier.

func (*Statement) Call

func (s *Statement) Call(params ...Code) *Statement

Call renders a comma separated list enclosed by parenthesis. Use for function calls.

func (*Statement) CallFunc

func (s *Statement) CallFunc(f func(*Group)) *Statement

CallFunc renders a comma separated list enclosed by parenthesis. Use for function calls.

func (*Statement) Cap

func (s *Statement) Cap(v Code) *Statement

Cap renders the cap built-in function.

func (*Statement) Case

func (s *Statement) Case(cases ...Code) *Statement

Case renders the keyword followed by a comma separated list.

func (*Statement) CaseFunc

func (s *Statement) CaseFunc(f func(*Group)) *Statement

CaseFunc renders the keyword followed by a comma separated list.

func (*Statement) Chan

func (s *Statement) Chan() *Statement

Chan renders the chan keyword.

func (*Statement) Clone

func (s *Statement) Clone() *Statement

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) Close

func (s *Statement) Close(c Code) *Statement

Close renders the close built-in function.

func (*Statement) Comment

func (s *Statement) Comment(str string) *Statement

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

func (s *Statement) Commentf(format string, a ...interface{}) *Statement

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) Complex

func (s *Statement) Complex(r Code, i Code) *Statement

Complex renders the complex built-in function.

func (*Statement) Complex128

func (s *Statement) Complex128() *Statement

Complex128 renders the complex128 identifier.

func (*Statement) Complex64

func (s *Statement) Complex64() *Statement

Complex64 renders the complex64 identifier.

func (*Statement) Const

func (s *Statement) Const() *Statement

Const renders the const keyword.

func (*Statement) Continue

func (s *Statement) Continue() *Statement

Continue renders the continue keyword.

func (*Statement) Copy

func (s *Statement) Copy(dst Code, src Code) *Statement

Copy renders the copy built-in function.

func (*Statement) Default

func (s *Statement) Default() *Statement

Default renders the default keyword.

func (*Statement) Defer

func (s *Statement) Defer() *Statement

Defer renders the defer keyword.

func (*Statement) Defs

func (s *Statement) Defs(definitions ...Code) *Statement

Defs renders a statement list enclosed in parenthesis. Use for definition lists.

func (*Statement) DefsFunc

func (s *Statement) DefsFunc(f func(*Group)) *Statement

DefsFunc renders a statement list enclosed in parenthesis. Use for definition lists.

func (*Statement) Delete

func (s *Statement) Delete(m Code, key Code) *Statement

Delete renders the delete built-in function.

func (*Statement) Do

func (s *Statement) Do(f func(*Statement)) *Statement

Do calls the provided function with the statement as a parameter. Use for embedding logic.

func (*Statement) Dot added in v0.11.0

func (s *Statement) Dot(name string) *Statement

Dot renders a period followed by an identifier. Use for fields and selectors.

func (*Statement) Else

func (s *Statement) Else() *Statement

Else renders the else keyword.

func (*Statement) Empty

func (s *Statement) Empty() *Statement

Empty adds an empty item. Empty items render nothing but are followed by a separator in lists.

func (*Statement) Err

func (s *Statement) Err() *Statement

Err renders the err identifier.

func (*Statement) Error

func (s *Statement) Error() *Statement

Error renders the error identifier.

func (*Statement) Fallthrough

func (s *Statement) Fallthrough() *Statement

Fallthrough renders the fallthrough keyword.

func (*Statement) False

func (s *Statement) False() *Statement

False renders the false identifier.

func (*Statement) Float32

func (s *Statement) Float32() *Statement

Float32 renders the float32 identifier.

func (*Statement) Float64

func (s *Statement) Float64() *Statement

Float64 renders the float64 identifier.

func (*Statement) For

func (s *Statement) For(conditions ...Code) *Statement

For renders the keyword followed by a semicolon separated list.

func (*Statement) ForFunc

func (s *Statement) ForFunc(f func(*Group)) *Statement

ForFunc renders the keyword followed by a semicolon separated list.

func (*Statement) Func

func (s *Statement) Func() *Statement

Func renders the func keyword.

func (*Statement) Go

func (s *Statement) Go() *Statement

Go renders the go keyword.

func (*Statement) GoString

func (s *Statement) GoString() string

GoString renders the Statement for testing. Any error will cause a panic.

func (*Statement) Goto

func (s *Statement) Goto() *Statement

Goto renders the goto keyword.

func (*Statement) Id

func (s *Statement) Id(name string) *Statement

Id renders an identifier.

func (*Statement) If

func (s *Statement) If(conditions ...Code) *Statement

If renders the keyword followed by a semicolon separated list.

func (*Statement) IfFunc

func (s *Statement) IfFunc(f func(*Group)) *Statement

IfFunc renders the keyword followed by a semicolon separated list.

func (*Statement) Imag

func (s *Statement) Imag(c Code) *Statement

Imag renders the imag built-in function.

func (*Statement) Index

func (s *Statement) Index(items ...Code) *Statement

Index renders a colon separated list enclosed by square brackets. Use for array / slice indexes and definitions.

func (*Statement) IndexFunc

func (s *Statement) IndexFunc(f func(*Group)) *Statement

IndexFunc renders a colon separated list enclosed by square brackets. Use for array / slice indexes and definitions.

func (*Statement) Int

func (s *Statement) Int() *Statement

Int renders the int identifier.

func (*Statement) Int16

func (s *Statement) Int16() *Statement

Int16 renders the int16 identifier.

func (*Statement) Int32

func (s *Statement) Int32() *Statement

Int32 renders the int32 identifier.

func (*Statement) Int64

func (s *Statement) Int64() *Statement

Int64 renders the int64 identifier.

func (*Statement) Int8

func (s *Statement) Int8() *Statement

Int8 renders the int8 identifier.

func (*Statement) Interface

func (s *Statement) Interface(methods ...Code) *Statement

Interface renders the keyword followed by a method list enclosed by curly braces.

func (*Statement) InterfaceFunc

func (s *Statement) InterfaceFunc(f func(*Group)) *Statement

InterfaceFunc renders the keyword followed by a method list enclosed by curly braces.

func (*Statement) Iota

func (s *Statement) Iota() *Statement

Iota renders the iota identifier.

func (*Statement) Len

func (s *Statement) Len(v Code) *Statement

Len renders the len built-in function.

func (*Statement) Line

func (s *Statement) Line() *Statement

Line inserts a blank line.

func (*Statement) List

func (s *Statement) List(items ...Code) *Statement

List renders a comma separated list. Use for multiple return functions.

func (*Statement) ListFunc

func (s *Statement) ListFunc(f func(*Group)) *Statement

ListFunc renders a comma separated list. Use for multiple return functions.

func (*Statement) Lit

func (s *Statement) Lit(v interface{}) *Statement

Lit renders a literal, using the format provided by the fmt package %#v verb.

func (*Statement) LitByte added in v0.13.0

func (s *Statement) LitByte(v byte) *Statement

LitByte renders a byte literal.

func (*Statement) LitByteFunc added in v0.13.0

func (s *Statement) LitByteFunc(f func() byte) *Statement

LitByteFunc renders a byte literal. LitByteFunc generates the value to render by executing the provided function.

func (*Statement) LitFunc

func (s *Statement) LitFunc(f func() interface{}) *Statement

LitFunc renders a literal, using the format provided by the fmt package %#v verb. LitFunc generates the value to render by executing the provided function.

func (*Statement) LitRune added in v0.13.0

func (s *Statement) LitRune(v rune) *Statement

LitRune renders a rune literal.

func (*Statement) LitRuneFunc added in v0.13.0

func (s *Statement) LitRuneFunc(f func() rune) *Statement

LitRuneFunc renders a rune literal. LitRuneFunc generates the value to render by executing the provided function.

func (*Statement) Make

func (s *Statement) Make(args ...Code) *Statement

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

func (s *Statement) Map(typ Code) *Statement

Map renders the keyword followed by a single item enclosed by square brackets. Use for map definitions.

func (*Statement) New

func (s *Statement) New(typ Code) *Statement

New renders the new built-in function.

func (*Statement) Nil

func (s *Statement) Nil() *Statement

Nil renders the nil identifier.

func (*Statement) Null

func (s *Statement) Null() *Statement

Null adds a null item. Null items render nothing and are not followed by a separator in lists.

func (*Statement) Op

func (s *Statement) Op(op string) *Statement

Op renders the provided operator / token.

func (*Statement) Panic

func (s *Statement) Panic(v Code) *Statement

Panic renders the panic built-in function.

func (*Statement) Params

func (s *Statement) Params(params ...Code) *Statement

Params renders a comma separated list enclosed by parenthesis. Use for function parameters and method receivers.

func (*Statement) ParamsFunc

func (s *Statement) ParamsFunc(f func(*Group)) *Statement

ParamsFunc renders a comma separated list enclosed by parenthesis. Use for function parameters and method receivers.

func (*Statement) Parens

func (s *Statement) Parens(item Code) *Statement

Parens renders a single item in parenthesis. Use for type conversion or to specify evaluation order.

func (*Statement) Print

func (s *Statement) Print(args ...Code) *Statement

Print renders the print built-in function.

func (*Statement) PrintFunc added in v0.9.1

func (s *Statement) PrintFunc(f func(*Group)) *Statement

PrintFunc renders the print built-in function.

func (*Statement) Println

func (s *Statement) Println(args ...Code) *Statement

Println renders the println built-in function.

func (*Statement) PrintlnFunc added in v0.9.1

func (s *Statement) PrintlnFunc(f func(*Group)) *Statement

PrintlnFunc renders the println built-in function.

func (*Statement) Qual

func (s *Statement) Qual(path, name string) *Statement

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.

func (*Statement) Range

func (s *Statement) Range() *Statement

Range renders the range keyword.

func (*Statement) Real

func (s *Statement) Real(c Code) *Statement

Real renders the real built-in function.

func (*Statement) Recover

func (s *Statement) Recover() *Statement

Recover renders the recover built-in function.

func (*Statement) Render added in v0.15.0

func (s *Statement) Render(writer io.Writer) error

Render renders the Statement to the provided writer.

func (*Statement) Return

func (s *Statement) Return(results ...Code) *Statement

Return renders the keyword followed by a comma separated list.

func (*Statement) ReturnFunc

func (s *Statement) ReturnFunc(f func(*Group)) *Statement

ReturnFunc renders the keyword followed by a comma separated list.

func (*Statement) Rune

func (s *Statement) Rune() *Statement

Rune renders the rune identifier.

func (*Statement) Select

func (s *Statement) Select() *Statement

Select renders the select keyword.

func (*Statement) String

func (s *Statement) String() *Statement

String renders the string identifier.

func (*Statement) Struct

func (s *Statement) Struct(fields ...Code) *Statement

Struct renders the keyword followed by a field list enclosed by curly braces.

func (*Statement) StructFunc added in v0.9.3

func (s *Statement) StructFunc(f func(*Group)) *Statement

StructFunc renders the keyword followed by a field list enclosed by curly braces.

func (*Statement) Switch

func (s *Statement) Switch(conditions ...Code) *Statement

Switch renders the keyword followed by a semicolon separated list.

func (*Statement) SwitchFunc

func (s *Statement) SwitchFunc(f func(*Group)) *Statement

SwitchFunc renders the keyword followed by a semicolon separated list.

func (*Statement) Tag

func (s *Statement) Tag(items map[string]string) *Statement

Tag renders a struct tag

func (*Statement) True

func (s *Statement) True() *Statement

True renders the true identifier.

func (*Statement) Type

func (s *Statement) Type() *Statement

Type renders the type keyword.

func (*Statement) Uint

func (s *Statement) Uint() *Statement

Uint renders the uint identifier.

func (*Statement) Uint16

func (s *Statement) Uint16() *Statement

Uint16 renders the uint16 identifier.

func (*Statement) Uint32

func (s *Statement) Uint32() *Statement

Uint32 renders the uint32 identifier.

func (*Statement) Uint64

func (s *Statement) Uint64() *Statement

Uint64 renders the uint64 identifier.

func (*Statement) Uint8

func (s *Statement) Uint8() *Statement

Uint8 renders the uint8 identifier.

func (*Statement) Uintptr

func (s *Statement) Uintptr() *Statement

Uintptr renders the uintptr identifier.

func (*Statement) Values

func (s *Statement) Values(values ...Code) *Statement

Values renders a comma separated list enclosed by curly braces. Use for slice or composite literals.

func (*Statement) ValuesFunc

func (s *Statement) ValuesFunc(f func(*Group)) *Statement

ValuesFunc renders a comma separated list enclosed by curly braces. Use for slice or composite literals.

func (*Statement) Var

func (s *Statement) Var() *Statement

Var renders the var keyword.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL