github.com/goplus/gox@v1.14.13-0.20240308130321-6ff7f61cfae8/README.md (about)

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