为什么要写这个

templatestringerstringerstringer
stringer

为啥要拿这个举例,因为有很多的文章都是这个,所以我们也用这个来弄。

Stringer is a tool to automate the creation of methods that satisfy the fmt.Stringer interface. Given the name of a (signed or unsigned) integer type T that has constants defined, stringer will create a new self-contained Go source file implementing

这个是 https://pkg.go.dev/golang.org/x/tools/cmd/stringer 里面的说明。看起来很麻烦,简单点说就是生成了一个 string 方法。

const iota

看下面之前最好先看看 https://xie.infoq.cn/article/e7a2d044bafbf474706e441cc 比我写的细致的多。

我们直接上个代码吧,根据官方例子来的

package main

import "fmt"

//go:generate stringer -type=Pill
type Pill int

const (
	Placebo Pill = iota // pla
	Aspirin // asp
	Ibuprofen // ibup
	Paracetamol // pa
	Acetaminophen = Paracetamol
)

func main() {
	fmt.Println(Placebo)
}
go generaterun
http
package main

import "fmt"

//go:generate stringer -type=HttpErrorCode -linecomment
type HttpErrorCode int

const (
	HTTP_OK HttpErrorCode = 200 // 访问成功
	HTTP_NOT_FOUNT HttpErrorCode = 404 // 404 不存在
	HTTP_SERVICE_UNAVAILABLE HttpErrorCode = 503 // 503 服务端错误
)

func main() {
	fmt.Println(HTTP_OK)
	fmt.Println(HTTP_OK == 201)
}

通过这个就可以看出来,我们只要写好说明,剩下的就全靠生成就好了,从此节省生命 1s。

template

用 template 一般都是用来生成代码文件,比如数据库生成 model,根据model 生成基础 curd 代码,不过这段,暂时先不弄示例,我还得在学习学习,然后等以后再 实例 的时候在加上来就好了

写在正文之后

距离上次写东西已经过去4个月了,最近几个月不知道自己都在干什么,东西看了不少,输出也不少,但要说有什么可写的,那几乎就是 0 了。今天终于弄出来一个了。