### NewFile example Source: https://deepwiki.com/dave/jennifer/1.1-installation-and-setup Creates a new file with the specified package name using NewFile. ```go f := NewFile("main") ``` -------------------------------- ### NewFilePathName example Source: https://deepwiki.com/dave/jennifer/1.1-installation-and-setup Creates a new file with the specified package path and name. ```go f := NewFilePathName("github.com/example/pkg", "main") ``` -------------------------------- ### NewFilePath example Source: https://deepwiki.com/dave/jennifer/1.1-installation-and-setup Creates a new file for the specified package path, inferring the package name. ```go f := NewFilePath("github.com/example/pkg") ``` -------------------------------- ### Install Jennifer with go get Source: https://deepwiki.com/dave/jennifer/1.1-installation-and-setup Use this command to install the Jennifer library for projects not using Go modules. It fetches the latest version of the package. ```bash go get -u github.com/dave/jennifer/jen ``` -------------------------------- ### Expected output of Hello, world program Source: https://deepwiki.com/dave/jennifer/1.1-installation-and-setup The expected output when Jennifer is installed correctly, showing a properly formatted Go program. ```go package main import "fmt" func main() { fmt.Println("Hello, world") } ``` -------------------------------- ### Hello, world program using Jennifer Source: https://deepwiki.com/dave/jennifer/1.1-installation-and-setup Creates a Go program that generates a 'Hello, world' program using Jennifer's dot import. Outputs the generated code with fmt.Printf. ```go package main import ( "fmt" . "github.com/dave/jennifer/jen" ) func main() { f := NewFile("main") f.Func().Id("main").Params().Block( Qual("fmt", "Println").Call(Lit("Hello, world")), ) fmt.Printf("%#v", f) } ``` -------------------------------- ### Standard import usage Source: https://deepwiki.com/dave/jennifer/1.1-installation-and-setup Imports Jennifer using the standard import style, requiring the 'jen' prefix for all calls. ```go import "github.com/dave/jennifer/jen" ``` -------------------------------- ### Rendering to a Writer with f.Render Source: https://deepwiki.com/dave/jennifer/1.2-quick-start Render the generated code to any io.Writer using the Render method. The example writes to a bytes.Buffer and handles errors. ```go f := NewFile("main") // ... add code ... buf := &bytes.Buffer{} err := f.Render(buf) if err != nil { // Handle error } ``` -------------------------------- ### Using Chained Method Calls Source: https://deepwiki.com/dave/jennifer/1.2-quick-start Jennifer's fluent interface allows chaining method calls. This example creates a function call with parameters using Qual, Call, Lit, and Id. ```go // This creates a function call with parameters Qual("fmt", "Printf").Call( Lit("%s: %d\n"), Id("name"), Id("age"), ) ``` -------------------------------- ### Saving to a File with f.Save Source: https://deepwiki.com/dave/jennifer/1.2-quick-start Save the generated code directly to a file using the Save method. The example saves to "main.go" and handles errors. ```go f := NewFile("main") // ... add code ... err := f.Save("main.go") if err != nil { // Handle error } ``` -------------------------------- ### Using Func Methods for Dynamic Code Source: https://deepwiki.com/dave/jennifer/1.2-quick-start Use *Func methods to dynamically generate repetitive code. This example generates a slice literal with values 0 through 5. ```go // Dynamically generate a slice Id("numbers").Op(":=").Index().Int().ValuesFunc(func(g *Group) { for i := 0; i <= 5; i++ { g.Lit(i) } }) ``` ```go numbers := []int{0, 1, 2, 3, 4, 5} ``` -------------------------------- ### Dot import usage Source: https://deepwiki.com/dave/jennifer/1.1-installation-and-setup Imports Jennifer using the dot import style, allowing direct calls without the 'jen' prefix. ```go import . "github.com/dave/jennifer/jen" ``` -------------------------------- ### Render generated code to a writer Source: https://deepwiki.com/dave/jennifer/1.1-installation-and-setup Use the Render method to output generated code to a writer. The code is formatted using Go's standard formatting rules unless NoFormat is set to true. ```go err := f.Render(writer) ``` -------------------------------- ### Manual Import Control Source: https://deepwiki.com/dave/jennifer/1.2-quick-start Shows how to manually control imports: add an alias, use an underscore import, or specify a package name. ```go // Add an import with an alias f.ImportAlias("github.com/foo/a", "bar") // Import a package without using it (underscore import) f.Anon("github.com/foo/a") // Specify the name for a package f.ImportName("github.com/foo/a", "foo") ``` -------------------------------- ### Create Variables and Constants Source: https://deepwiki.com/dave/jennifer/1.2-quick-start Shows how to declare a variable, assign a value, and define constants using Jennifer's Var, Id, and Const methods. ```go // Variable declaration f.Var().Id("name").String() // Variable assignment f.Id("name").Op(":=").Lit("John") // Constants f.Const().Defs( Id("Pi").Op("=").Lit(3.14), Id("Version").Op("=").Lit("1.0"), ) ``` -------------------------------- ### Standard Library Imports Example Source: https://deepwiki.com/dave/jennifer/4-import-management Shows how Jennifer resolves standard library package names using Qual(). The generated code imports 'fmt' and 'os/exec' with their canonical names. ```go f := NewFile("main") f.Func().Id("main").Params().Block( Qual("fmt", "Println").Call(Lit("Hello")), Qual("os/exec", "Command").Call(Lit("ls")), ) ``` ```go package main import ( "fmt" "os/exec" ) func main() { fmt.Println("Hello") exec.Command("ls") } ``` -------------------------------- ### Automatic Imports with Qual Source: https://deepwiki.com/dave/jennifer/1.2-quick-start Shows how Qual automatically adds imports for fmt and os. The generated code includes the import block. ```go // Using Qual automatically adds imports f.Func().Id("main").Params().Block( Qual("fmt", "Println").Call(Lit("Hello")), Qual("os", "Exit").Call(Lit(0)), ) ``` ```go package main import ( "fmt" "os" ) func main() { fmt.Println("Hello") os.Exit(0) } ``` -------------------------------- ### Save generated code to a file Source: https://deepwiki.com/dave/jennifer/1.1-installation-and-setup Use the Save method to write generated code directly to a file. The code is formatted using Go's standard formatting rules unless NoFormat is set to true. ```go err := f.Save("output.go") ``` -------------------------------- ### Generate Hello World Program Source: https://deepwiki.com/dave/jennifer/1.2-quick-start Creates a Go program that prints 'Hello, world' using Jennifer's fluent API. The generated code is printed with fmt.Printf. ```go package main import ( "fmt" . "github.com/dave/jennifer/jen" ) func main() { f := NewFile("main") f.Func().Id("main").Params().Block( Qual("fmt", "Println").Call(Lit("Hello, world")), ) fmt.Printf("%#v", f) } ``` ```go package main import "fmt" func main() { fmt.Println("Hello, world") } ``` -------------------------------- ### Built-in Function Examples Source: https://deepwiki.com/dave/jennifer/3.3-functions-and-methods Examples of using Jennifer methods for Go built-in functions. Each row shows the method call for the corresponding built-in. ```go Append(Id("slice"), Id("item")) ``` ```go Cap(Id("slice")) ``` ```go Close(Id("ch")) ``` ```go Complex(Lit(1), Lit(2)) ``` ```go Copy(Id("dst"), Id("src")) ``` ```go Delete(Id("m"), Id("key")) ``` ```go Len(Id("s")) ``` ```go Make(Chan().Int()) ``` ```go New(Int()) ``` ```go Panic(Lit("error")) ``` ```go Recover() ``` ```go Println(Id("x")) ``` -------------------------------- ### Conflict Resolution Example Source: https://deepwiki.com/dave/jennifer/4-import-management Demonstrates automatic conflict resolution when two external packages share the same last path component. Jennifer appends numbers to avoid name collisions. ```go f := NewFile("main") f.Func().Id("main").Params().Block( Qual("github.com/bar/a", "Bar").Call(), Qual("github.com/foo/a", "Foo").Call(), ) ``` ```go package main import ( a "github.com/bar/a" a1 "github.com/foo/a" ) func main() { a.Bar() a1.Foo() } ``` -------------------------------- ### Avoiding Statement Reuse Issues with Clone Source: https://deepwiki.com/dave/jennifer/1.2-quick-start When reusing a statement, use Clone() to avoid unexpected behavior. The example shows incorrect reuse without Clone and correct reuse with Clone. ```go // Without Clone (incorrect) a := Id("a") block1 := Block( a.Call(), a.Call(), ) ``` ```go // With Clone (correct) a := Id("a") block2 := Block( a.Clone().Call(), a.Clone().Call(), ) ``` -------------------------------- ### Printing for Testing with fmt.Printf Source: https://deepwiki.com/dave/jennifer/1.2-quick-start Use fmt.Printf with the %#v verb to quickly print generated code for testing. This method panics on errors and is not recommended for production use. ```go f := NewFile("main") // ... add code ... fmt.Printf("%#v", f) ``` -------------------------------- ### Generate For Loop Source: https://deepwiki.com/dave/jennifer/1.2-quick-start Creates a for loop that iterates from 0 to 9 and prints each value. The generated code shows the resulting Go loop. ```go // For loop f.For( Id("i").Op(":=").Lit(0), Id("i").Op("<").Lit(10), Id("i").Op("++"), ).Block( Qual("fmt", "Println").Call(Id("i")), ) ``` ```go for i := 0; i < 10; i++ { fmt.Println(i) } ``` -------------------------------- ### Create Files with NewFile, NewFilePath, NewFilePathName Source: https://deepwiki.com/dave/jennifer/1.2-quick-start Shows three ways to create a Jennifer file: with a package name, with a package path, and with both. Each returns a file object for further code generation. ```go // Create a new file with package name "main" f := NewFile("main") // Create a file with a specific package path f := NewFilePath("a.b/c") // Create a file with a specific package path and name f := NewFilePathName("a.b/c", "main") ``` -------------------------------- ### Generate Map Literal Source: https://deepwiki.com/dave/jennifer/1.2-quick-start Creates a map with string keys and values. The generated code shows the resulting Go map literal. ```go // Create a map f.Id("users").Op(":=").Map(String()).String().Values(Dict{ Lit("admin"): Lit("password"), Lit("guest"): Lit("guest"), }) ``` ```go users := map[string]string{ "admin": "password", "guest": "guest", } ``` -------------------------------- ### Fluent interface example: create main function with Println call Source: https://deepwiki.com/dave/jennifer Shows the fluent interface pattern where methods return the receiver for chaining. Builds a Go file with a main function that calls fmt.Println with a literal string. ```go f := NewFile("main") f.Func().Id("main").Params().Block( Qual("fmt", "Println").Call(Lit("Hello, world")), ) ``` -------------------------------- ### Comprehensive Example: Adding Comments to a File Source: https://deepwiki.com/dave/jennifer/3.5-comments-and-documentation Shows how to add header, package, and inline comments to a generated Go file. The output includes the generated code with comments placed appropriately. ```go f := NewFile("a") f.HeaderComment("Code generated by Jennifer. DO NOT EDIT.") f.PackageComment("Package a provides utility functions for working with strings.") f.Comment("Foo returns the string \"foo\"") f.Func().Id("Foo").Params().String().Block( Return(Lit("foo")).Comment("return the string foo"), ) ``` ```go // Code generated by Jennifer. DO NOT EDIT. // Package a provides utility functions for working with strings. package a // Foo returns the string "foo" func Foo() string { return "foo" // return the string foo } ``` -------------------------------- ### Slice indexing and slicing examples Source: https://deepwiki.com/dave/jennifer/3.4-data-structures Shows three slicing operations: a := b[0:1], a := b[1:], and a := b[:]. Each uses Index with Lit and Empty. ```go // Generates: a := b[0:1] Id("a").Op(":=").Id("b").Index(Lit(0), Lit(1)) ``` ```go // Generates: a := b[1:] Id("a").Op(":=").Id("b").Index(Lit(1), Empty()) ``` ```go // Generates: a := b[:] Id("a").Op(":=").Id("b").Index(Empty(), Empty()) ``` -------------------------------- ### Generate Function Declaration Source: https://deepwiki.com/dave/jennifer/1.2-quick-start Creates a function declaration with parameters and a return type. The generated code shows the resulting Go function. ```go // Function declaration f.Func().Id("add").Params( Id("a").Int(), Id("b").Int(), ).Int().Block( Return(Id("a").Op("+").Id("b")), ) ``` ```go func add(a int, b int) int { return a + b } ``` -------------------------------- ### Generate Slice Literal Source: https://deepwiki.com/dave/jennifer/1.2-quick-start Creates a slice of integers with three elements. The generated code shows the resulting Go slice literal. ```go // Create a slice f.Id("numbers").Op(":=").Index().Int().Values( Lit(1), Lit(2), Lit(3), ) ``` ```go numbers := []int{1, 2, 3} ``` -------------------------------- ### go:generate directives for genjen and gennames Source: https://deepwiki.com/dave/jennifer/6.1-code-generation-tools Integrates both tools into Jennifer's build process. Running `go generate` installs and executes the latest versions of genjen and gennames, generating up-to-date code. ```go //go:generate go install github.com/dave/jennifer/genjen@latest //go:generate genjen //go:generate go install github.com/dave/jennifer/gennames@latest //go:generate gennames -output "jen/hints.go" -package "jen" -name "standardLibraryHints" -standard -novendor -path "./..." ``` -------------------------------- ### Create goroutines with Go() Source: https://deepwiki.com/dave/jennifer/3.2-control-flow Use Go() to generate a goroutine. The example shows a goroutine that receives from a channel and calls cancel(). ```go // Generates: // go func() { // <-c // cancel() // }() Go().Func().Params().Block( Op("<-").Id("c"), Id("cancel").Call(), ).Call() ``` -------------------------------- ### Return statement Source: https://deepwiki.com/dave/jennifer/3-code-generation-api Builds a return statement with multiple values. The example generates 'return a, b'. ```go Return(Id("a"), Id("b")) ``` ```go return a, b ``` -------------------------------- ### Go Statements Source: https://deepwiki.com/dave/jennifer/3.2-control-flow Create goroutines with the `Go()` function. The example shows a goroutine that waits on a channel and then calls a cancel function. ```APIDOC ## Go Statements ### Description Create goroutines with the `Go()` function. ### Usage ```go // Generates: // go func() { // <-c // cancel() // }() Go().Func().Params().Block( Op("<-").Id("c"), Id("cancel").Call(), ).Call() ``` ### Sources - jen/generated.go2509-2534 - jen/examples_test.go937-941 ``` -------------------------------- ### Package Comment Example Source: https://deepwiki.com/dave/jennifer/3.5-comments-and-documentation Adds a package comment immediately before the package declaration, typically documenting the package's purpose. The comment is rendered as a line comment directly above the package clause. ```go f := NewFile("c") f.PackageComment("Package c implements...") ``` ```go // Package c implements... package c ``` -------------------------------- ### Define Struct with Tags Source: https://deepwiki.com/dave/jennifer/1.2-quick-start Defines a struct with fields and a JSON tag on the Address field. The generated code shows the resulting Go struct. ```go // Define a struct f.Type().Id("Person").Struct( Id("Name").String(), Id("Age").Int(), Id("Address").String().Tag(map[string]string{"json": "address"}), ) ``` ```go type Person struct { Name string Age int Address string `json:"address"` } ``` -------------------------------- ### Header Comment Example Source: https://deepwiki.com/dave/jennifer/3.5-comments-and-documentation Adds a header comment at the top of the generated file, typically used for license or generation metadata. The comment is rendered as a line comment before the package declaration. ```go f := NewFile("c") f.HeaderComment("Code generated by...") ``` ```go // Code generated by... package c ``` -------------------------------- ### Generated Code for Anonymous Function Source: https://deepwiki.com/dave/jennifer/3.3-functions-and-methods Shows the Go code generated by the previous anonymous function example. ```go handler := func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello, %s!", r.URL.Path) } ``` -------------------------------- ### Generate defer statements Source: https://deepwiki.com/dave/jennifer/3.2-control-flow Use Defer() to generate a defer statement. The example shows deferring a call to foo(). ```go // Generates: defer foo() Defer().Id("foo").Call() ``` -------------------------------- ### Basic CGO Example: Generate C function call with preamble Source: https://deepwiki.com/dave/jennifer/5.2-cgo-integration Generates Go code that defines a C function in the preamble and calls it from Go. The CGO preamble is rendered as a comment block before the 'C' import, which is placed after regular imports. The generated code includes the preamble and the C function call. ```go f := NewFile("main") f.CgoPreamble(`#include #include void myprint(char* s) { printf("%s\n", s); }`) f.Func().Id("main").Params().Block( Id("cs").Op(":=").Qual("C", "CString").Call(Lit("Hello from C")), Qual("C", "myprint").Call(Id("cs")), Qual("C", "free").Call(Qual("unsafe", "Pointer").Parens(Id("cs"))), ) ``` ```go package main import "unsafe" /* #include #include void myprint(char* s) { printf("%s\n", s); } */ import "C" func main() { cs := C.CString("Hello from C") C.myprint(cs) C.free(unsafe.Pointer(cs)) } ``` -------------------------------- ### Function Parameters with Params() and Return() Source: https://deepwiki.com/dave/jennifer/3-code-generation-api Creates a method with parameters and a return statement. The example generates a function that returns the sum of two strings. ```go Func().Params( Id("a").Id("A"), ).Id("foo").Params( Id("b"), Id("c").String(), ).String().Block( Return(Id("b").Op("+").Id("c")), ) ``` ```go func (a A) foo(b, c string) string { return b + c } ``` -------------------------------- ### Creating a map literal with Dict Source: https://deepwiki.com/dave/jennifer/3.1-identifiers-and-literals Use the Dict type to create a map literal with key-value pairs. The example generates a map[string]string with the specified entries. ```go // Creating a map literal with key-value pairs Map(String()).String().Values(Dict{ Lit("a"): Lit("b"), Lit("c"): Lit("d"), }) ``` ```go map[string]string{ "a": "b", "c": "d", } ``` -------------------------------- ### For loop construct Source: https://deepwiki.com/dave/jennifer/3-code-generation-api Builds a for loop with initialization, condition, and post statement. The example generates a loop that prints numbers 0 through 9. ```go For( Id("i").Op(":=").Lit(0), Id("i").Op("<").Lit(10), Id("i").Op("++"), ).Block( Qual("fmt", "Println").Call(Id("i")), ) ``` ```go for i := 0; i < 10; i++ { fmt.Println(i) } ``` -------------------------------- ### Custom rendering with Options struct Source: https://deepwiki.com/dave/jennifer/5-advanced-topics Defines a multi-line call with custom delimiters and separator using the Options struct. The example renders as a multi-line function call with each argument on its own line. ```go multiLineCall := Options{ Close: ")", Multi: true, Open: "(", Separator: ",", } c := Id("foo").Custom(multiLineCall, Lit("a"), Lit("b"), Lit("c")) ``` ```text foo( "a", "b", "c", ) ``` -------------------------------- ### Struct Definition with Type().Struct() Source: https://deepwiki.com/dave/jennifer/3-code-generation-api Builds a struct type with fields. The example generates a struct with an int field and a float32 field. ```go Type().Id("foo").Struct( List(Id("x"), Id("y")).Int(), Id("u").Float32(), ) ``` ```go type foo struct { x, y int u float32 } ``` -------------------------------- ### Statement Chaining Source: https://deepwiki.com/dave/jennifer/3-code-generation-api Demonstrates method chaining in the jen API. The example chains Id, Op, Index, Dot, and Call to generate a statement. The generated code is shown. ```go Id("a").Op(":=").Id("b").Index(Lit(0)).Dot("c").Call() ``` ```go a := b[0].c() ``` -------------------------------- ### Benchmark Jennifer code generation with Go's built-in benchmarking Source: https://deepwiki.com/dave/jennifer/5.3-performance-considerations Use Go's testing package to benchmark code generation performance. The loop runs b.N times, and the example includes a placeholder for your generation logic before rendering to a buffer. ```go func BenchmarkCodeGeneration(b *testing.B) { for i := 0; i < b.N; i++ { f := NewFile("main") // Your code generation logic here buf := &bytes.Buffer{} f.Render(buf) } } ``` -------------------------------- ### Generate Switch Statement Source: https://deepwiki.com/dave/jennifer/1.2-quick-start Creates a switch statement that checks the Kind of a value and returns a string based on the type. Uses reflect package qualifiers. ```go // Switch statement f.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")), ), Default().Block( Return(Lit("none")), ), ) ``` -------------------------------- ### Monitor memory usage during large code generation Source: https://deepwiki.com/dave/jennifer/5.3-performance-considerations Track memory allocation before and after generation using runtime.ReadMemStats. The example prints memory usage in MB and includes placeholders for your large generation logic. ```go func generateLargeFile() { f := NewFile("main") // Add memory usage tracking var m runtime.MemStats runtime.ReadMemStats(&m) fmt.Printf("Before generation: %v MB\n", m.Alloc/1024/1024) // Your large code generation runtime.ReadMemStats(&m) fmt.Printf("After generation: %v MB\n", m.Alloc/1024/1024) } ``` -------------------------------- ### Using Op() to add operators and symbols Source: https://deepwiki.com/dave/jennifer/3-code-generation-api Shows how to use the Op() function to add operators, special characters, and symbols to a statement. The examples demonstrate chaining Op() with Id() and Call() to produce expressions like 'a = *b', 'a != nil', and 'a(b...)'. ```go Id("a").Op("=").Op("*").Id("b") // a = *b Id("a").Op("!=").Nil() // a != nil Id("a").Call(Id("b").Op("...")) // a(b...) ``` -------------------------------- ### Qual function: reference identifier from package Source: https://deepwiki.com/dave/jennifer/3-code-generation-api References an identifier from a specific package, generating a qualified call. The example generates 'fmt.Println("Hello")'. ```go Qual("fmt", "Println").Call(Lit("Hello")) // Generates: fmt.Println("Hello") ``` -------------------------------- ### Create and save a Go file with jen.NewFile Source: https://deepwiki.com/dave/jennifer/2.4-file Shows how to instantiate a File, add imports, define a main function, and save it to disk. The generated file includes the package declaration, imports, and the main function. ```go // Create a new file f := jen.NewFile("main") // Add imports f.ImportName("net/http", "http") f.Anon("_ context") // Add a function f.Func().Id("main").Params().Block( jen.Qual("fmt", "Println").Call(jen.Lit("Hello, world!")), ) // Save to file f.Save("main.go") ``` -------------------------------- ### Generate goto statements and labels Source: https://deepwiki.com/dave/jennifer/3.2-control-flow Use Goto() to generate a goto statement and Id().Op(":") to generate a label. The example shows generating 'goto Label' and 'Label:'. ```go // Generates: goto Label Goto().Id("Label") // Generates: Label: Id("Label").Op(":") ``` -------------------------------- ### Function Calls with Call() Source: https://deepwiki.com/dave/jennifer/3.3-functions-and-methods Generates function calls using Call() with a list of arguments. The example shows calls to fmt.Println and fmt.Printf, and an empty Call() for no arguments. ```go Id("fmt").Dot("Println").Call(Lit("Hello")) // fmt.Println("Hello") Qual("fmt", "Printf").Call(Lit("%d"), Id("count")) // fmt.Printf("%d", count) ``` ```go Id("f").Call() // f() ``` -------------------------------- ### Comment Formatting Disabled Example Source: https://deepwiki.com/dave/jennifer/3.5-comments-and-documentation Preserves custom formatting in comments by using specific syntax. Jennifer keeps the formatting exactly as provided, including spaces and comment markers. ```go Id("foo").Call(Comment("/* inline */")).Comment("//no-space") ``` ```go foo( /* inline */ ) //no-space ``` -------------------------------- ### Create return statements with single or multiple values Source: https://deepwiki.com/dave/jennifer/3.2-control-flow Use Return() with one or more arguments to generate return statements. The example shows returning a single variable 'a' and two variables 'a, b'. ```go // Generates: return a Return(Id("a")) // Generates: return a, b Return(Id("a"), Id("b")) ``` -------------------------------- ### Basic Type Parameters with Types() Source: https://deepwiki.com/dave/jennifer/3.6-generics Generates a generic function with type parameters using the Types() method. The example creates a function F with type parameters K and V, constrained by comparable and any, and a map parameter. ```go // func F[K comparable, V any](m map[K]V) []K {} Func().Id("F").Types( Id("K").Comparable(), Id("V").Any(), ).Params( Id("m").Map(Id("K")).Id("V"), ).Index().Id("K").Block() ``` -------------------------------- ### Using Null() and Empty() for special tokens Source: https://deepwiki.com/dave/jennifer/3-code-generation-api Demonstrates the Null() function for creating an ignored item and Empty() for creating an empty item, particularly for slice indices. The example shows how to generate 'a := b[1:]' using Index() with Lit() and Empty(). ```go Id("a").Op(":=").Id("b").Index(Lit(1), Empty()) // a := b[1:] ``` -------------------------------- ### Using BlockFunc() for complex structures Source: https://deepwiki.com/dave/jennifer/3-code-generation-api Tip: For complex structures, use the *Func variants for cleaner code. The example shows how to use BlockFunc() with a function that takes a *Group to add statements. ```go BlockFunc(func(g *Group) { g.Id("a").Op("=").Lit(1) g.Id("b").Op("=").Lit(2) }) ``` -------------------------------- ### LitByte and LitRune: special literals Source: https://deepwiki.com/dave/jennifer/3-code-generation-api Creates byte and rune literals using dedicated functions. The example shows generated byte and rune literals. ```go LitByte(byte(1)) // byte(0x1) LitRune('x') // 'x' ``` -------------------------------- ### Generated Code for Anonymous Function with Go Source: https://deepwiki.com/dave/jennifer/3.3-functions-and-methods Shows the Go code generated by the previous anonymous function with go statement example. ```go go func() { doWork() }() ``` -------------------------------- ### Select Statement with Select() and Case() Source: https://deepwiki.com/dave/jennifer/3.2-control-flow Creates a Go select statement for channel operations. The example includes cases for receiving from a done channel and a fail channel with a check for open status. ```go // Generates: // select { // case <-done: // return nil // case err, open := <-fail: // if !open { // return err // } // } 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()), ), ), ) ``` -------------------------------- ### Function Declaration with Func().Id().Params().Block() Source: https://deepwiki.com/dave/jennifer/3-code-generation-api Builds a Go function declaration with a block body. The example generates a main function that prints 'Hello, world'. ```go Func().Id("main").Params().Block( Qual("fmt", "Println").Call(Lit("Hello, world")), ) ``` ```go func main() { fmt.Println("Hello, world") } ``` -------------------------------- ### Method Calls with Dot() and Call() Source: https://deepwiki.com/dave/jennifer/3.3-functions-and-methods Constructs method calls by chaining Dot() and Call(). The examples show calling Save() on user and Close() on resp.Body. ```go Id("user").Dot("Save").Call() // user.Save() Id("resp").Dot("Body").Dot("Close").Call() // resp.Body.Close() ``` -------------------------------- ### Method Declaration with Receiver Source: https://deepwiki.com/dave/jennifer/3.3-functions-and-methods Declares a method with a pointer receiver using Params() before the method name. The example generates a method Area() on *Rectangle that returns the product of width and height. ```go Func().Params( Id("r").Op("*").Id("Rectangle"), ).Id("Area").Params().Float64().Block( Return(Id("r").Dot("width").Op("*").Id("r").Dot("height")), ) ``` ```go func (r *Rectangle) Area() float64 { return r.width * r.height } ``` -------------------------------- ### Switch-Case construct Source: https://deepwiki.com/dave/jennifer/3-code-generation-api Builds a switch statement with cases and a default. The example generates a switch on value.Kind() that returns "float" for float types and "unknown" otherwise. ```go Switch(Id("value").Dot("Kind").Call()).Block( Case(Qual("reflect", "Float32"), Qual("reflect", "Float64")).Block( Return(Lit("float")), ), Default().Block( Return(Lit("unknown")), ), ) ``` ```go switch value.Kind() { case reflect.Float32, reflect.Float64: return "float" default: return "unknown" } ``` -------------------------------- ### If-Else construct Source: https://deepwiki.com/dave/jennifer/3-code-generation-api Builds an if-else block. The example generates an if statement that divides 'a' by 2 when 'a' is greater than 10. ```go If(Id("a").Op(">").Lit(10)).Block( Id("a").Op("=").Id("a").Op("/").Lit(2), ) ``` ```go if a > 10 { a = a / 2 } ``` -------------------------------- ### Using Clone() to avoid side effects when reusing Statement objects Source: https://deepwiki.com/dave/jennifer/3-code-generation-api Tip: Use Clone() when reusing Statement objects to avoid unintended side effects. The example shows how to call the same identifier twice without modifying the original 'a'. ```go a := Id("a") Block( a.Clone().Call(), // Use Clone to avoid modifying 'a' a.Clone().Call(), ) ``` -------------------------------- ### Generate If Statement Source: https://deepwiki.com/dave/jennifer/1.2-quick-start Creates an if statement that checks an error from a function call. The generated code shows the resulting Go if block. ```go // If statement f.If( Err().Op(":=").Id("someFunc").Call(), Err().Op("!=").Nil(), ).Block( Return(Err()), ) ``` ```go if err := someFunc(); err != nil { return err } ``` -------------------------------- ### CGO Import with f.CgoPreamble Source: https://deepwiki.com/dave/jennifer/4-import-management Handles the special C pseudo-package for CGO. The C package is automatically handled as a special case during import resolution. ```go f := NewFile("a") f.CgoPreamble(`#include `) f.Func().Id("main").Params().Block( Qual("C", "Foo").Call(), ) ``` -------------------------------- ### Interface Definition with Type().Interface() Source: https://deepwiki.com/dave/jennifer/3-code-generation-api Creates an interface type with method signatures. The example generates an interface with two methods. ```go Type().Id("foo").Interface( Id("bar").Params().String(), Id("baz").Params(Id("i").Int()).Error(), ) ``` ```go type foo interface { bar() string baz(i int) error } ``` -------------------------------- ### Break and Continue Source: https://deepwiki.com/dave/jennifer/3.2-control-flow Generate `break` and `continue` statements using the corresponding functions. The example shows a `for` loop with a conditional `break`. ```APIDOC ## Break and Continue ### Description Generate `break` and `continue` statements using the corresponding functions. ### Usage ```go // Generates: // for i := 0; i < 10; i++ { // if i > 5 { // break // } // } For( Id("i").Op(":=").Lit(0), Id("i").Op("<").Lit(10), Id("i").Op("++"), ).Block( If(Id("i").Op(">").Lit(5)).Block( Break(), ), ) ``` ### Sources - jen/generated.go2185-2208 - jen/generated.go2413-2433 - jen/examples_test.go767-784 ``` -------------------------------- ### Basic usage with ImportName Source: https://deepwiki.com/dave/jennifer/4.2-manual-import-control Shows how to specify a package name with ImportName and use Qual to reference it. The output shows the generated Go code with the import and function call. ```go f := NewFile("main") // Specify package name f.ImportName("github.com/foo/a", "a") f.Func().Id("main").Params().Block( Qual("github.com/foo/a", "A").Call(), ) ``` ```go package main import "github.com/foo/a" func main() { a.A() } ``` -------------------------------- ### NewFile(packageName string) Source: https://deepwiki.com/dave/jennifer/2.4-file Creates a new File with the specified package name. Use this when you only care about the package name. ```APIDOC ## NewFile(packageName string) ### Description Creates a new File with the specified package name. Use this when you only care about the package name. ### Method Constructor ### Parameters - **packageName** (string) - Required - The package name for the file. ### Returns - **File** - A new File instance. ``` -------------------------------- ### Local Package Handling with Qual Source: https://deepwiki.com/dave/jennifer/4-import-management When a file references its own package, Jennifer automatically omits the qualifier. The generated code calls the function without a package prefix. ```go f := NewFilePath("a.b/c") f.Func().Id("main").Params().Block( Qual("a.b/c", "Foo").Call(), // Local package - no qualifier ) ``` ```go package c func main() { Foo() // No package qualifier } ``` -------------------------------- ### Slice Literal with Index().Values() Source: https://deepwiki.com/dave/jennifer/3-code-generation-api Builds a slice literal with string elements. The example generates a slice with two string values. ```go Index().String().Values(Lit("a"), Lit("b")) ``` ```go []string{"a", "b"} ``` -------------------------------- ### Map Literal with Map().Values() Source: https://deepwiki.com/dave/jennifer/3-code-generation-api Generates a map literal with string keys and values. The example produces a map with two entries. ```go Map(String()).String().Values(Dict{ Lit("a"): Lit("b"), Lit("c"): Lit("d"), }) ``` ```go map[string]string{ "a": "b", "c": "d", } ``` -------------------------------- ### CgoPreamble with C function call Source: https://deepwiki.com/dave/jennifer/5-advanced-topics Adds a C preamble and uses Qual("C", ...) to call C functions. The generated code places the preamble in a comment before the C import and imports "unsafe" for the pointer conversion. ```go f := NewFile("a") f.CgoPreamble(`#include #include 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"))), ) ``` ```go package a import "unsafe" /* #include #include 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)) } ``` -------------------------------- ### Dot function: add dot selector Source: https://deepwiki.com/dave/jennifer/3-code-generation-api Adds a dot selector to access a field or method on an identifier. The example generates 'foo.Bar'. ```go Id("foo").Dot("Bar") // Generates: foo.Bar ``` -------------------------------- ### Inline Comment Example Source: https://deepwiki.com/dave/jennifer/3.5-comments-and-documentation Adds a comment to a statement, placing it at the end of the line. The comment is rendered as a trailing line comment after the generated code. ```go Id("foo").Call().Comment("calls foo") ``` ```go foo() // calls foo ``` -------------------------------- ### Basic Function Declaration with Statement Source: https://deepwiki.com/dave/jennifer/2.2-statement Creates a statement representing a function declaration with a body containing a single function call. Uses the fluent interface to build the function structure. ```go statement := file.Func().Id("main").Params().Block( Qual("fmt", "Println").Call(Lit("something")), ) ``` -------------------------------- ### Function Call with Id().Call() Source: https://deepwiki.com/dave/jennifer/3-code-generation-api Generates a function call with literal arguments. The example produces a call to foo with two string literals. ```go Id("foo").Call(Lit("a"), Lit("b")) ``` ```go foo("a", "b") ``` -------------------------------- ### Using dot imports for multiple packages Source: https://deepwiki.com/dave/jennifer/4.2-manual-import-control Creates dot imports for multiple packages using ImportAlias with '.'. The output shows the generated import block with dot imports and unqualified calls. ```go f := NewFile("main") // Create dot-imports for multiple packages f.ImportAlias("github.com/foo/a", ".") f.ImportAlias("github.com/foo/b", ".") f.Func().Id("main").Params().Block( Qual("github.com/foo/a", "A").Call(), Qual("github.com/foo/b", "B").Call(), ) ``` ```go package main import ( . "github.com/foo/a" . "github.com/foo/b" ) func main() { A() B() } ``` -------------------------------- ### Do Source: https://deepwiki.com/dave/jennifer/2.2-statement Executes a function with the statement as parameter. ```APIDOC ## Do ### Description Executes a function with the statement as parameter. ### Method Do(f func(*Statement)) ### Parameters - **f** (func(*Statement)) - The function to execute. ``` -------------------------------- ### Statement render method Source: https://deepwiki.com/dave/jennifer/2.2-statement Processes each code item in the statement, separating them with spaces. Skips nil or null items and writes a space before each non-first item. ```go func (s *Statement) render(f *File, w io.Writer, _ *Statement) error { first := true for _, code := range *s { if code == nil || code.isNull(f) { continue } if !first { if _, err := w.Write([]byte(" ")); err != nil { return err } } if err := code.render(f, w, s); err != nil { return err } first = false } return nil } ``` -------------------------------- ### Qual Source: https://deepwiki.com/dave/jennifer/2.2-statement Adds a qualified identifier with import path. ```APIDOC ## Qual ### Description Adds a qualified identifier with import path. ### Method Qual(path, name string) ### Parameters - **path** (string) - The import path. - **name** (string) - The identifier name. ``` -------------------------------- ### Using Qual to Generate Import Source: https://deepwiki.com/dave/jennifer/4.1-automatic-import-resolution Use the Qual method to reference an external package in generated code. The system automatically adds the import statement for the package path. ```go // This generates: fmt.Println("Hello, world") // And automatically adds: import "fmt" f := jen.NewFile("main") f.Func().Id("main").Params().Block( jen.Qual("fmt", "Println").Call(jen.Lit("Hello, world")), ) ``` -------------------------------- ### ImportNames: Set multiple names at once Source: https://deepwiki.com/dave/jennifer/4-import-management Use ImportNames to set multiple package names at once by providing a map of package paths to names. ```go names := map[string]string{ "github.com/foo/a": "a", "github.com/foo/b": "b", } f.ImportNames(names) ``` -------------------------------- ### NewFilePathName(packagePath, packageName string) Source: https://deepwiki.com/dave/jennifer/2.4-file Creates a new File with a specific package path and a custom package name. Use this when you need both the path and a custom name. ```APIDOC ## NewFilePathName(packagePath, packageName string) ### Description Creates a new File with a specific package path and a custom package name. Use this when you need both the path and a custom name. ### Method Constructor ### Parameters - **packagePath** (string) - Required - The package path for the file. - **packageName** (string) - Required - The custom package name for the file. ### Returns - **File** - A new File instance. ``` -------------------------------- ### Statement Reuse With Clone (Correct Code) Source: https://deepwiki.com/dave/jennifer/5.3-performance-considerations Shows the correct approach when reusing a statement in multiple contexts. Cloning the statement before each call ensures each use operates on an independent copy, producing the expected output. ```go // With Clone (correct) a := Id("a") c := Block( a.Clone().Call(), // Uses a clone of a a.Clone().Call(), // Uses another clone of a ) // Renders as: { a() a() } ``` -------------------------------- ### Id function: generate identifier call Source: https://deepwiki.com/dave/jennifer/3-code-generation-api Creates an identifier reference such as a variable, function, or type name. The example generates a call to the identifier 'foo'. ```go Id("foo").Call() // Generates: foo() ``` -------------------------------- ### Anonymous Functions Source: https://deepwiki.com/dave/jennifer/3.3-functions-and-methods Declares an anonymous function using Func() without an Id(). The example shows how to create a handler function that writes a greeting to the response. ```APIDOC ## Anonymous Functions ### Description Declares an anonymous function using `Func()` without an `Id()`. The example shows how to create a handler function that writes a greeting to the response. ### Method N/A (Code generation API) ### Endpoint N/A ### Parameters N/A ### Response N/A ### Request Example ```go Id("handler").Op(":=").Func().Params( Id("w").Qual("net/http", "ResponseWriter"), Id("r").Op("*").Qual("net/http", "Request"), ).Block( Qual("fmt", "Fprintf").Call(Id("w"), Lit("Hello, %s!"), Id("r").Dot("URL").Dot("Path")), ) ``` ### Response Example ```go handler := func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello, %s!", r.URL.Path) } ``` ``` -------------------------------- ### Generated standardLibraryHints map Source: https://deepwiki.com/dave/jennifer/6.1-code-generation-tools Output of the gennames tool: a Go file with a map from import paths to package names, used by Jennifer's import management. The file is generated and should not be edited. ```go // This file is generated - do not edit. // standardLibraryHints contains package name hints var standardLibraryHints = map[string]string{ "archive/tar": "tar", "archive/zip": "zip", // ... many more entries } ``` -------------------------------- ### CgoPreamble(comment string) Source: https://deepwiki.com/dave/jennifer/2.4-file Adds a CGO preamble comment before the "C" import. This method is used to insert a CGO preamble comment into the generated code. ```APIDOC ## CgoPreamble(comment string) ### Description Adds a CGO preamble comment before the "C" import. ### Method CgoPreamble ### Parameters - **comment** (string) - Required - The comment text to add. ``` -------------------------------- ### Add CGO preamble with CgoPreamble Source: https://deepwiki.com/dave/jennifer/5.2-cgo-integration Use the CgoPreamble method on a File to include C code in the generated Go file. The preamble is rendered as a comment block before the import "C" statement. Multiple calls add sections in order. ```go f := NewFile("main") f.CgoPreamble(`#include #include void myprint(char* s) { printf("%s\n", s); }`) ``` -------------------------------- ### CallFunc for Dynamic Arguments Source: https://deepwiki.com/dave/jennifer/3.3-functions-and-methods Uses CallFunc() to generate call arguments dynamically inside a callback. The example iterates over a slice and adds each value as a literal argument. ```go Id("fmt").Dot("Println").CallFunc(func(g *Group) { for _, val := range values { g.Lit(val) } }) ```