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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值