search
HomeBackend DevelopmentGolangWhat is the function of go generate command?

What is the function of go generate command?

Jan 30, 2023 pm 03:07 PM
golanggo language

The "go generate" command is used to automatically generate certain types of code before compilation; it is often used to automatically generate code, and it can generate code based on source code before the code is compiled. When the "go generate" command is run, it will scan the source code files related to the current package, find all special comments containing "//go:generate", extract and execute the command following the special comment.

What is the function of go generate command?

The operating environment of this tutorial: Windows 7 system, GO version 1.18, Dell G3 computer.

Go language provides a series of powerful tools. Flexible use of these tools can make our project development easier. The toolset includes the following.

bug         start a bug report
build       compile packages and dependencies
clean       remove object files and cached files
doc         show documentation for package or symbol
env         print Go environment information
fix         update packages to use new APIs
fmt         gofmt (reformat) package sources
generate    generate Go files by processing source
get         add dependencies to current module and install them
install     compile and install packages and dependencies
list        list packages or modules
mod         module maintenance
run         compile and run Go program
test        test packages
tool        run specified go tool
version     print Go version
vet         report likely mistakes in packages

The source code of the tool is located in $GOPATH/src/cmd/internal. This article mainly discusses the Go tool generate.

go language automation tool


The go generate command is a newly added command in Go language version 1.4, which is often used for automatic Generate code, which generates code from source code before the code is compiled. When running go generate, it will scan the source code files related to the current package, find all comment statements containing "//go:generate", extract and execute the command after the comment, and the command will be an executable program. The process is similar to calling and executing a shell script.

Usage method

  • Add special comments
//go:generate command argument...
  • Execute the generate command
$ go generate [-run regexp] [-n] [-v] [-x] [build flags] [file.go... | packages]

Note

  • This special comment is required Contained in the .go source code file.
  • Each source code file can contain multiple generate special comments.
  • go generate will not be triggered by commands such as go build, go get, go test, etc., and must be used explicitly by the developer.
  • Command execution is serial. If an error occurs, subsequent commands will not be executed.
  • Special comments must start with "//go:generate", with no space after the double slash.
  • The execution command must be an executable program under the system PATH (echo $PATH).

Usage example

package mainimport "fmt"//go:generate echo GoGoGo!//go:generate go run main.go//go:generate echo $GOARCH $GOOS $GOFILE $GOLINE $GOPACKAGEfunc main() {
 fmt.Println("go rum main.go!")}

Execute go generate command

$ go generate
GoGoGo!go rum main.go!amd64 darwin main.go 7 main

Implementing String method for enumeration constants


After reading the above brief introduction of generate, readers may not feel the power of this tool. Xiaocai Knife provides a The classic application scenario of this tool: implementing the String method for enumeration constants.

Another official tool, stringer, needs to be mentioned here, which can automatically write the String() method for a set of integer constants. Since stringer is not in the tool set of the official Go release, we need to install it ourselves and execute the following command.

go get golang.org/x/tools/cmd/stringer

Here is an example quoted from the stringer documentation. The code is as follows, which defines a set of integer constants of different Pill types.

package painkillertype Pill intconst (
    Placebo Pill = iota
    Aspirin
    Ibuprofen
    Paracetamol
    Acetaminophen = Paracetamol)

For debugging or other reasons, we want these constants to be printed, which means Pill must have a signed method.

func (p Pill) String() string

To achieve it, it is very simple.

func (p Pill) String() string {
    switch p {
    case Placebo:
        return "Placebo"
    case Aspirin:
        return "Aspirin"
    case Ibuprofen:
        return "Ibuprofen"
    case Paracetamol: // == Acetaminophen
        return "Paracetamol"
    }
    return fmt.Sprintf("Pill(%d)", p)}

Just imagine, if a batch of new drug names are added to our Pill list, every time the drug name is added or modified, the corresponding signature function also needs to be changed. Wouldn't this be cumbersome and likely to be missed or wrong? At this time, we can solve this problem through go generate stringer. It's very simple, just add a comment statement to the code that defines Pill.

//go:generate stringer -type=Pill

The above command represents running the stringer tool to generate a String method for the Pill type. By default, it is output to the pill_string.go file. The execution is as follows.

$ go generate
$ cat pill_string.go
// Code generated by stringer -type Pill pill.go; DO NOT EDIT.

package painkillerimport "fmt"const _Pill_name = "PlaceboAspirinIbuprofenParacetamol"var _Pill_index = [...]uint8{0, 7, 14, 23, 34}func (i Pill) String() string {
    if i = Pill(len(_Pill_index)) {
        return fmt.Sprintf("Pill(%d)", i)
    }
    return _Pill_name[_Pill_index[i]:_Pill_index[i+1]]}

In this way, every time we modify the Pill type, all we need to do is run the following statement.

$ go generate

Of course, if you find this troublesome, or are worried about forgetting to execute the generate statement. Then, you can write the go generate statement into the Makefile and place it before the go build command to automate code generation and compilation.

It is worth mentioning that in the Go source code documents, the go generate stringer solution is widely used to implement the String method for enumeration constants. Under the source code of Xiaocai Knife's native Go 1.14.1, there are a total of 23 uses, as follows.

What is the function of go generate command?

Summary


This article mainly introduces what generate is, what it can do, if you want To deeply understand its internal implementation logic, you can look at the detailed process of generating code in the Go source code, such as the generation of zfuncversion.go through genzfunc.go under the sort package. In the Go source code treasure house, you can find many similar implementation logics, please refer to the following.

What is the function of go generate command?

They use the libraries provided by the Go compiler, including go/ast for defining abstract syntax trees, go/parser for parsing abstract syntax trees, go/format for parsing code formatting, and go/ for Go lexical tags. token, etc. Parse the source file and generate new code according to the existing template. This process is similar to using templates to generate HTML files in Web services.

【Related recommendations: Go video tutorial, Programming teaching

The above is the detailed content of What is the function of go generate command?. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Choosing Between Golang and Python: The Right Fit for Your ProjectChoosing Between Golang and Python: The Right Fit for Your ProjectApr 19, 2025 am 12:21 AM

Golangisidealforperformance-criticalapplicationsandconcurrentprogramming,whilePythonexcelsindatascience,rapidprototyping,andversatility.1)Forhigh-performanceneeds,chooseGolangduetoitsefficiencyandconcurrencyfeatures.2)Fordata-drivenprojects,Pythonisp

Golang: Concurrency and Performance in ActionGolang: Concurrency and Performance in ActionApr 19, 2025 am 12:20 AM

Golang achieves efficient concurrency through goroutine and channel: 1.goroutine is a lightweight thread, started with the go keyword; 2.channel is used for secure communication between goroutines to avoid race conditions; 3. The usage example shows basic and advanced usage; 4. Common errors include deadlocks and data competition, which can be detected by gorun-race; 5. Performance optimization suggests reducing the use of channel, reasonably setting the number of goroutines, and using sync.Pool to manage memory.

Golang vs. Python: Which Language Should You Learn?Golang vs. Python: Which Language Should You Learn?Apr 19, 2025 am 12:20 AM

Golang is more suitable for system programming and high concurrency applications, while Python is more suitable for data science and rapid development. 1) Golang is developed by Google, statically typing, emphasizing simplicity and efficiency, and is suitable for high concurrency scenarios. 2) Python is created by Guidovan Rossum, dynamically typed, concise syntax, wide application, suitable for beginners and data processing.

Golang vs. Python: Performance and ScalabilityGolang vs. Python: Performance and ScalabilityApr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Golang vs. Other Languages: A ComparisonGolang vs. Other Languages: A ComparisonApr 19, 2025 am 12:11 AM

Go language has unique advantages in concurrent programming, performance, learning curve, etc.: 1. Concurrent programming is realized through goroutine and channel, which is lightweight and efficient. 2. The compilation speed is fast and the operation performance is close to that of C language. 3. The grammar is concise, the learning curve is smooth, and the ecosystem is rich.

Golang and Python: Understanding the DifferencesGolang and Python: Understanding the DifferencesApr 18, 2025 am 12:21 AM

The main differences between Golang and Python are concurrency models, type systems, performance and execution speed. 1. Golang uses the CSP model, which is suitable for high concurrent tasks; Python relies on multi-threading and GIL, which is suitable for I/O-intensive tasks. 2. Golang is a static type, and Python is a dynamic type. 3. Golang compiled language execution speed is fast, and Python interpreted language development is fast.

Golang vs. C  : Assessing the Speed DifferenceGolang vs. C : Assessing the Speed DifferenceApr 18, 2025 am 12:20 AM

Golang is usually slower than C, but Golang has more advantages in concurrent programming and development efficiency: 1) Golang's garbage collection and concurrency model makes it perform well in high concurrency scenarios; 2) C obtains higher performance through manual memory management and hardware optimization, but has higher development complexity.

Golang: A Key Language for Cloud Computing and DevOpsGolang: A Key Language for Cloud Computing and DevOpsApr 18, 2025 am 12:18 AM

Golang is widely used in cloud computing and DevOps, and its advantages lie in simplicity, efficiency and concurrent programming capabilities. 1) In cloud computing, Golang efficiently handles concurrent requests through goroutine and channel mechanisms. 2) In DevOps, Golang's fast compilation and cross-platform features make it the first choice for automation tools.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)