github.com/goplus/gogen@v1.16.0/README.md (about) 1 gogen - Code generator for the Go language 2 ======== 3 4 [![Build Status](https://github.com/goplus/gogen/actions/workflows/go.yml/badge.svg)](https://github.com/goplus/gogen/actions/workflows/go.yml) 5 [![Go Report Card](https://goreportcard.com/badge/github.com/goplus/gogen)](https://goreportcard.com/report/github.com/goplus/gogen) 6 [![GitHub release](https://img.shields.io/github/v/tag/goplus/gogen.svg?label=release)](https://github.com/goplus/gogen/releases) 7 [![Coverage Status](https://codecov.io/gh/goplus/gogen/branch/main/graph/badge.svg)](https://codecov.io/gh/goplus/gogen) 8 [![GoDoc](https://pkg.go.dev/badge/github.com/goplus/gogen.svg)](https://pkg.go.dev/github.com/goplus/gogen) 9 10 `gogen` is a general-purpose Go code generation toolkit. Like the Go compiler, It can perform type checking of expressions. For example, if you generate an expression like `"Hello" + 1`, it will report the corresponding error. 11 12 ## Quick start 13 14 Create a file named `hellogen.go`, like below: 15 16 ```go 17 package main 18 19 import ( 20 "go/token" 21 "go/types" 22 "os" 23 24 "github.com/goplus/gogen" 25 ) 26 27 func main() { 28 pkg := gogen.NewPackage("", "main", nil) 29 fmt := pkg.Import("fmt") 30 v := pkg.NewParam(token.NoPos, "v", types.Typ[types.String]) // v string 31 32 pkg.NewFunc(nil, "main", nil, nil, false).BodyStart(pkg). 33 DefineVarStart(token.NoPos, "a", "b").Val("Hi").Val(3).EndInit(2). // a, b := "Hi", 3 34 NewVarStart(nil, "c").VarVal("b").EndInit(1). // var c = b 35 NewVar(gogen.TyEmptyInterface, "x", "y"). // var x, y interface{} 36 Val(fmt.Ref("Println")). 37 /**/ VarVal("a").VarVal("b").VarVal("c"). // fmt.Println(a, b, c) 38 /**/ Call(3).EndStmt(). 39 NewClosure(gogen.NewTuple(v), nil, false).BodyStart(pkg). 40 /**/ Val(fmt.Ref("Println")).Val(v).Call(1).EndStmt(). // fmt.Println(v) 41 /**/ End(). 42 Val("Hello").Call(1).EndStmt(). // func(v string) { ... } ("Hello") 43 End() 44 45 pkg.WriteTo(os.Stdout) 46 } 47 ``` 48 49 Try it like: 50 51 ```shell 52 go mod init hello 53 go mod tidy 54 go run hellogen.go 55 ``` 56 57 This will dump Go source code to `stdout`. The following is the output content: 58 59 ```go 60 package main 61 62 import "fmt" 63 64 func main() { 65 a, b := "Hi", 3 66 var c = b 67 var x, y interface{} 68 fmt.Println(a, b, c) 69 func(v string) { 70 fmt.Println(v) 71 }("Hello") 72 } 73 ```