做了一個簡單的go generate工具,從go官方工具stringer修改而來,為結構體生成setter和getter。
結構體中欄位首字母大寫預設可讀可寫,小寫則預設只讀。
可以新增access的tag,控制訪問屬性r表示讀,w表示寫,用逗號分隔。
go get gitee.com/dwdcth/accessor
新增 go:generate accessor -type=Type1,Type2
Type1,Type2表示需要生成的型別,用逗號分隔
//go:generate accessor -type=Foo,Bar
package foobar
type Foo struct {
ReadWrite int `access:"r,w"`
Write int `access:"w"`
}
type Bar struct {
ReadWrite int
read int
}
會生成兩個檔案,foo_accessor.go 和 bar_accessor.go
foo_accessor.go
// Code generated by "accessor -type=Foo,Bar"; DO NOT EDIT.
package foobar
func (f *Foo) SetReadWrite(param int) {
f.ReadWrite = param
}
func (f *Foo) GetReadWrite() int {
return f.ReadWrite
}
func (f *Foo) SetWrite(param int) {
f.Write = param
}
bar_accessor.go
// Code generated by "accessor -type=Foo,Bar"; DO NOT EDIT.
package foobar
func (b *Bar) GetReadWrite() int {
return b.ReadWrite
}
func (b *Bar) SetReadWrite(param int) {
b.ReadWrite = param
}
func (b *Bar) Getread() int {
return b.read
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結