jen

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Oct 14, 2020 License: AGPL-3.0, MIT Imports: 10 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

func IsLine

func IsLine(t token) bool

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

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

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"

/*
#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) GoString

func (f *File) GoString() string

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

func (*File) HeaderComment

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

func (f *File) ImportAlias(path, alias string)

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

func (f *File) ImportName(path, name string)

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

func (f *File) ImportNames(names map[string]string)

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

func (f *File) PackageComment(comment string)

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

func (*File) PackageCommentf

func (f *File) PackageCommentf(comment string, args ...interface{})

PackageCommentf 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) AddressOf

func (g *Group) AddressOf() *Statement

AddressOf renders the provided operator / token.

func (*Group) And

func (g *Group) And() *Statement

And renders the provided operator / token.

func (*Group) Append

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

Append renders the append built-in function.

func (*Group) AppendFunc

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

func (g *Group) Assign() *Statement

Assign renders the colon equals ( `:=` ) operator

func (*Group) BitwiseOR

func (g *Group) BitwiseOR() *Statement

BitwiseOR renders the provided operator | token.

func (*Group) BitwiseXOR

func (g *Group) BitwiseXOR() *Statement

BitwiseXOR renders the provided operator ^ token.

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

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

Body 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) Callln

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

Callln 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) Caseln

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

Caseln 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) Custom

func (g *Group) Custom(options Options, statements ...Code) *Statement

Custom renders a customized statement list. Pass in options to specify multi-line, and tokens for open, close, separator.

func (*Group) CustomFunc

func (g *Group) CustomFunc(options Options, f func(*Group)) *Statement

CustomFunc renders a customized statement list. Pass in options to specify multi-line, and tokens for open, close, separator.

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

func (g *Group) DoesNotEqual() *Statement

DoesNotEqual renders the provided operator / token.

func (*Group) Dot

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

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

func (*Group) Dotf

func (g *Group) Dotf(name string, args ...interface{}) *Statement

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

func (*Group) Dotln

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

Dotln 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) EmptyString

func (g *Group) EmptyString() *Statement

EmptyString renders an empty string literal.

func (*Group) Equals

func (g *Group) Equals() *Statement

Equals renders the provided operator / token.

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

func (g *Group) GreaterThan() *Statement

GreaterThan renders the provided operator / token.

func (*Group) GreaterThanOrEqual

func (g *Group) GreaterThanOrEqual() *Statement

GreaterThanOrEqual renders the provided operator / token.

func (*Group) ID

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

ID renders an identifier.

func (*Group) IDf

func (g *Group) IDf(name string, args ...interface{}) *Statement

IDf 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) ImportBlock

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

ImportBlock renders a comma-and-newline separated list enclosed by curly braces. Use for slice or composite literals.

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

func (g *Group) IsEqualTo() *Statement

IsEqualTo renders the provided operator / token.

func (*Group) LeftShift

func (g *Group) LeftShift() *Statement

LeftShift renders the provided operator << token.

func (*Group) Len

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

Len renders the len built-in function.

func (*Group) LessThan

func (g *Group) LessThan() *Statement

LessThan renders the provided operator / token.

func (*Group) LessThanOrEqual

func (g *Group) LessThanOrEqual() *Statement

LessThanOrEqual renders the provided operator / token.

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

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

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

func (*Group) Lit

func (g *Group) 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.

func (*Group) LitByte

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

LitByte renders a byte literal.

func (*Group) LitByteFunc

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. 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) LitRune

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

LitRune renders a rune literal.

func (*Group) LitRuneFunc

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

func (g *Group) Litf(format string, args ...interface{}) *Statement

Litf renders a literal. Litf 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) 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) MapAssign

func (g *Group) MapAssign() *Statement

MapAssign renders the provided operator / token.

func (*Group) Minus

func (g *Group) Minus() *Statement

Minus renders the provided operator / token.

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

func (g *Group) Not() *Statement

Not renders the provided operator / token.

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

func (g *Group) One() *Statement

One renders an empty string literal.

func (*Group) Op

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

Op renders the provided operator / token.

func (*Group) Opln

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

Opln renders the provided operator / token.

func (*Group) Or

func (g *Group) Or() *Statement

Or renders an identifier.

func (*Group) PairedCallln

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

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

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

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

Paramsln renders a comma-and-newline 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) Plus

func (g *Group) Plus() *Statement

Plus renders the provided operator + token.

func (*Group) PlusEquals

func (g *Group) PlusEquals() *Statement

PlusEquals renders the provided operator += token.

func (*Group) PointerTo

func (g *Group) PointerTo() *Statement

PointerTo renders the provided operator / token.

func (*Group) Print

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

Print renders the print built-in function.

func (*Group) PrintFunc

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

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. 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) Range

func (g *Group) Range() *Statement

Range renders the range keyword.

func (*Group) RawString

func (g *Group) RawString(v string) *Statement

RawString 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) RawStringf

func (g *Group) RawStringf(msg string, args ...interface{}) *Statement

RawStringf 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) Real

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

Real renders the real built-in function.

func (*Group) ReceiveFromChannel

func (g *Group) ReceiveFromChannel() *Statement

ReceiveFromChannel renders the provided operator / token.

func (*Group) Receiver

func (g *Group) Receiver(receiver Code) *Statement

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

func (*Group) Recover

func (g *Group) Recover() *Statement

Recover renders the recover built-in function.

func (*Group) Render

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

Render renders the Group to the provided writer.

func (*Group) RenderWithFile

func (g *Group) RenderWithFile(writer io.Writer, file *File) error

RenderWithFile renders the Group to the provided writer, using imports from the provided file.

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

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

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

func (*Group) RightShift

func (g *Group) RightShift() *Statement

RightShift renders the provided operator >> token.

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

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

SingleLineBlock 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) Slice

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

Slice is an alias of INdex

func (*Group) Spread

func (g *Group) Spread() *Statement

Spread renders the provided operator ... token.

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

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

func (g *Group) Times() *Statement

Times renders the provided operator / token.

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

func (g *Group) Underscore() *Statement

Underscore renders an 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) Valuesln

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

Valuesln renders a comma-and-newline 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.

func (*Group) Zero

func (g *Group) Zero() *Statement

Zero renders an empty string literal.

type Options

type Options struct {
	Open      string
	Close     string
	Separator string
	Multi     bool
}

Options specifies options for the Custom method

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 AddressOf

func AddressOf() *Statement

AddressOf renders the provided operator / token.

func And

func And() *Statement

And renders the provided operator / token.

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

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 Assign

func Assign() *Statement

Assign renders the colon equals ( `:=` ) operator

func BitwiseOR

func BitwiseOR() *Statement

BitwiseOR renders the provided operator | token.

func BitwiseXOR

func BitwiseXOR() *Statement

BitwiseXOR renders the provided operator ^ token.

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 Body

func Body(statements ...Code) *Statement

Body 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 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 Callln

func Callln(params ...Code) *Statement

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

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 Caseln

func Caseln(cases ...Code) *Statement

Caseln renders the keyword followed by a comma separated list.

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 Custom

func Custom(options Options, statements ...Code) *Statement

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

func CustomFunc(options Options, f func(*Group)) *Statement

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

func DoesNotEqual() *Statement

DoesNotEqual renders the provided operator / token.

func Dot

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 Dotf

func Dotf(name string, args ...interface{}) *Statement

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

func Dotln

func Dotln(name string) *Statement

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

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 EmptyString

func EmptyString() *Statement

EmptyString renders an empty string literal.

func Equals

func Equals() *Statement

Equals renders the provided operator / token.

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 GreaterThan

func GreaterThan() *Statement

GreaterThan renders the provided operator / token.

func GreaterThanOrEqual

func GreaterThanOrEqual() *Statement

GreaterThanOrEqual renders the provided operator / token.

func ID

func ID(name string) *Statement

ID renders an identifier.

func IDf

func IDf(name string, args ...interface{}) *Statement

IDf renders an identifier.

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 ImportBlock

func ImportBlock(values ...Code) *Statement

ImportBlock renders a comma-and-newline separated list enclosed by curly braces. Use for slice or composite literals.

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 IsEqualTo

func IsEqualTo() *Statement

IsEqualTo renders the provided operator / token.

func LeftShift

func LeftShift() *Statement

LeftShift renders the provided operator << token.

func Len

func Len(v Code) *Statement

Len renders the len built-in function.

func LessThan

func LessThan() *Statement

LessThan renders the provided operator / token.

func LessThanOrEqual

func LessThanOrEqual() *Statement

LessThanOrEqual renders the provided operator / token.

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 Listln

func Listln(items ...Code) *Statement

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

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

func LitByte(v byte) *Statement

LitByte renders a byte literal.

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

byte(0x1)

func LitByteFunc

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

func LitRune(v rune) *Statement

LitRune renders a rune literal.

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

'x'

func LitRuneFunc

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 Litf

func Litf(format string, args ...interface{}) *Statement

Litf renders a literal. Litf 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 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 MapAssign

func MapAssign() *Statement

MapAssign renders the provided operator / token.

func Minus

func Minus() *Statement

Minus renders the provided operator / token.

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 Not

func Not() *Statement

Not renders the provided operator / token.

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 One

func One() *Statement

One renders an empty string literal.

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(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 Opln

func Opln(op string) *Statement

Opln renders the provided operator / token.

func Or

func Or() *Statement

Or renders an identifier.

func PairedCallln

func PairedCallln(params ...Code) *Statement

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

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 Paramsln

func Paramsln(params ...Code) *Statement

Paramsln renders a comma-and-newline 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 Plus

func Plus() *Statement

Plus renders the provided operator + token.

func PlusEquals

func PlusEquals() *Statement

PlusEquals renders the provided operator += token.

func PointerTo

func PointerTo() *Statement

PointerTo renders the provided operator / token.

func Print

func Print(args ...Code) *Statement

Print renders the print built-in function.

func PrintFunc

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

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. 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 Range

func Range() *Statement

Range renders the range keyword.

func RawString

func RawString(v string) *Statement

RawString 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 RawStringf

func RawStringf(msg string, args ...interface{}) *Statement

RawStringf 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 Real

func Real(c Code) *Statement

Real renders the real built-in function.

func ReceiveFromChannel

func ReceiveFromChannel() *Statement

ReceiveFromChannel renders the provided operator / token.

func Receiver

func Receiver(receiver Code) *Statement

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

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 ReturnParams

func ReturnParams(params ...Code) *Statement

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

func RightShift

func RightShift() *Statement

RightShift renders the provided operator >> token.

func Rune

func Rune() *Statement

Rune renders the rune identifier.

func Select

func Select() *Statement

Select renders the select keyword.

func SingleLineBlock

func SingleLineBlock(statements ...Code) *Statement

SingleLineBlock 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 Slice

func Slice(items ...Code) *Statement

Slice is an alias of INdex

func Spread

func Spread() *Statement

Spread renders the provided operator ... token.

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

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 Times

func Times() *Statement

Times renders the provided operator / token.

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 Underscore

func Underscore() *Statement

Underscore renders an 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 Valuesln

func Valuesln(values ...Code) *Statement

Valuesln renders a comma-and-newline separated list enclosed by curly braces. Use for slice or composite literals.

func Var

func Var() *Statement

Var renders the var keyword.

func Zero

func Zero() *Statement

Zero renders an empty string literal.

func (*Statement) Add

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

Add appends the provided items to the statement.

func (*Statement) AddressOf

func (s *Statement) AddressOf() *Statement

AddressOf renders the provided operator / token.

func (*Statement) And

func (s *Statement) And() *Statement

And renders the provided operator / token.

func (*Statement) Append

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

Append renders the append built-in function.

func (*Statement) AppendFunc

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

func (s *Statement) Assign() *Statement

Assign renders the colon equals ( `:=` ) operator

func (*Statement) BitwiseOR

func (s *Statement) BitwiseOR() *Statement

BitwiseOR renders the provided operator | token.

func (*Statement) BitwiseXOR

func (s *Statement) BitwiseXOR() *Statement

BitwiseXOR renders the provided operator ^ token.

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

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

Body 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) Callln

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

Callln 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) Caseln

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

Caseln 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) Custom

func (s *Statement) Custom(options Options, statements ...Code) *Statement

Custom renders a customized statement list. Pass in options to specify multi-line, and tokens for open, close, separator.

func (*Statement) CustomFunc

func (s *Statement) CustomFunc(options Options, f func(*Group)) *Statement

CustomFunc renders a customized statement list. Pass in options to specify multi-line, and tokens for open, close, separator.

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

func (s *Statement) DoesNotEqual() *Statement

DoesNotEqual renders the provided operator / token.

func (*Statement) Dot

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

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

func (*Statement) Dotf

func (s *Statement) Dotf(name string, args ...interface{}) *Statement

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

func (*Statement) Dotln

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

Dotln 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) EmptyString

func (s *Statement) EmptyString() *Statement

EmptyString renders an empty string literal.

func (*Statement) Equals

func (s *Statement) Equals() *Statement

Equals renders the provided operator / token.

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

func (s *Statement) GreaterThan() *Statement

GreaterThan renders the provided operator / token.

func (*Statement) GreaterThanOrEqual

func (s *Statement) GreaterThanOrEqual() *Statement

GreaterThanOrEqual renders the provided operator / token.

func (*Statement) ID

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

ID renders an identifier.

func (*Statement) IDf

func (s *Statement) IDf(name string, args ...interface{}) *Statement

f 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) ImportBlock

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

ImportBlock renders a comma-and-newline separated list enclosed by curly braces. Use for slice or composite literals.

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

func (s *Statement) IsEqualTo() *Statement

IsEqualTo renders the provided operator / token.

func (*Statement) LeftShift

func (s *Statement) LeftShift() *Statement

LeftShift renders the provided operator << token.

func (*Statement) Len

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

Len renders the len built-in function.

func (*Statement) LessThan

func (s *Statement) LessThan() *Statement

LessThan renders the provided operator / token.

func (*Statement) LessThanOrEqual

func (s *Statement) LessThanOrEqual() *Statement

LessThanOrEqual renders the provided operator / token.

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

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

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

func (*Statement) Lit

func (s *Statement) 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.

func (*Statement) LitByte

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

LitByte renders a byte literal.

func (*Statement) LitByteFunc

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. 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) LitRune

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

LitRune renders a rune literal.

func (*Statement) LitRuneFunc

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

func (s *Statement) Litf(format string, args ...interface{}) *Statement

Litf renders a literal. Litf 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) 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) MapAssign

func (s *Statement) MapAssign() *Statement

MapAssign renders the provided operator / token.

func (*Statement) Minus

func (s *Statement) Minus() *Statement

Minus renders the provided operator / token.

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

func (s *Statement) Not() *Statement

Not renders the provided operator / token.

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

func (s *Statement) One() *Statement

One renders an empty string literal.

func (*Statement) Op

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

Op renders the provided operator / token.

func (*Statement) Opln

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

Opln renders the provided operator / token.

func (*Statement) Or

func (s *Statement) Or() *Statement

Or renders an identifier.

func (*Statement) PairedCallln

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

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

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

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

Paramsln renders a comma-and-newline 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) Plus

func (s *Statement) Plus() *Statement

Plus renders the provided operator + token.

func (*Statement) PlusEquals

func (s *Statement) PlusEquals() *Statement

PlusEquals renders the provided operator += token.

func (*Statement) PointerTo

func (s *Statement) PointerTo() *Statement

PointerTo renders the provided operator / token.

func (*Statement) Print

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

Print renders the print built-in function.

func (*Statement) PrintFunc

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

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. 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) Range

func (s *Statement) Range() *Statement

Range renders the range keyword.

func (*Statement) RawString

func (s *Statement) RawString(v string) *Statement

RawString 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) RawStringf

func (s *Statement) RawStringf(msg string, args ...interface{}) *Statement

RawStringf 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) Real

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

Real renders the real built-in function.

func (*Statement) ReceiveFromChannel

func (s *Statement) ReceiveFromChannel() *Statement

ReceiveFromChannel renders the provided operator / token.

func (*Statement) Receiver

func (s *Statement) Receiver(receiver Code) *Statement

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

func (*Statement) Recover

func (s *Statement) Recover() *Statement

Recover renders the recover built-in function.

func (*Statement) Render

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

Render renders the Statement to the provided writer.

func (*Statement) RenderWithFile

func (s *Statement) RenderWithFile(writer io.Writer, file *File) error

RenderWithFile renders the Statement to the provided writer, using imports from the provided file.

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

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

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

func (*Statement) RightShift

func (s *Statement) RightShift() *Statement

RightShift renders the provided operator >> token.

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

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

SingleLineBlock 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) Slice

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

Slice is an alias of INdex

func (*Statement) Spread

func (s *Statement) Spread() *Statement

Spread renders the provided operator ... token.

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

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

func (s *Statement) Times() *Statement

Times renders the provided operator / token.

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

func (s *Statement) Underscore() *Statement

Underscore renders an 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) Valuesln

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

Valuesln renders a comma-and-newline 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.

func (*Statement) Zero

func (s *Statement) Zero() *Statement

Zero renders an empty string literal.

Jump to

Keyboard shortcuts

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