go generate命令有啥作用呢?

go generate命令其实就是用来生成代码用的,一般情况下需要配置其他工具和库一起使用
go官网有个实例:

painkiller.go

package painkiller
 
type Pill int

const (

    Placebo Pill = iota

    Aspirin

    Ibuprofen

    Paracetamol

    Acetaminophen = Paracetamol

)

假设我们现在需要为painkiller.go 中的常量添加String方法,我们可以这样写

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)

}

如果我们用go generate 来自动化生成代码呢?

在 painkiller.go 最开头处添加

//go:generate stringer -type=Pill

因为要用到工具stringer,所以我们通过命令安装

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

然后在painkiller目录执行go generate,会生成一个pill_string.go的文件:

// Code generated by "stringer -type=Pill"; DO NOT EDIT.

package painkiller

import "strconv"

const _Pill_name = "PlaceboAspirinIbuprofenParacetamol"

var _Pill_index = [...]uint8{0, 7, 14, 23, 34}

func (i Pill) String() string {
	if i < 0 || i >= Pill(len(_Pill_index)-1) {
		return "Pill(" + strconv.FormatInt(int64(i), 10) + ")"
	}
	return _Pill_name[_Pill_index[i]:_Pill_index[i+1]]
}

原文地址:https://www.cnblogs.com/linyihai/p/10513512.html