Generate accessors for each field in the slice struct.
- Easy Setup & Removal
- Code Generation & Zero Package Size
$ go install github.com/snamiki1212/go-gen-slice-accessors@latest
$ go-gen-slice-accessors --help
# -> To ensure it was installed correctly, otherwise set up your GOPATH like `export PATH=$PATH:$(go env GOPATH)/bin`
// user.go
package main
+//go:generate go-gen-slice-accessors --entity User --slice Users --input user.go --output user_gen.go
type User struct {
UserID string
}
type Users []User
$ go generate user.go
+// Code generated by go generate DO NOT EDIT.
+
+package main
+
+// UserIDs
+func (xs Users) UserIDs() []string {
+ sli := make([]string, 0, len(xs))
+ for i := range xs {
+ sli = append(sli, xs[i].UserID)
+ }
+ return sli
+}
package main
import "fmt"
func main() {
us := Users{{UserID: "1"}, {UserID: "2"}, {UserID: "3"}}
ids := us.UserIDs() // 🚀 You can use accessors for slice.
fmt.Println(ids) // [1 2 3]
}
Tip
Recommended to install a binary with go:generate
and skip the installation command but simly run go generate
.
+//go:generate go install github.com/snamiki1212/go-gen-slice-accessors@latest
+//go:generate go-gen-slice-accessors --entity User --slice Users --input user.go --output user_gen.go
type User struct {
...
Generate accessors for each field in the slice struct.
Usage:
gen-slice-accessors [flags]
Flags:
-e, --entity string [required] Target entity name
-x, --exclude strings Field names to exclude
-h, --help help for gen-slice-accessors
-m, --import strings Import path name
e.g. --import=time
e.g. --import=time:aliasTime
-i, --input string [required] Input file name
-o, --output string [required] Output file name
-r, --rename strings Rename accessor name
e.g. --rename=Name:GetName
-s, --slice string [required] Target slice name
- Common case: input → output
- Private field case: input → output
- Exclude flag: input → output
- Rename flag: input → output
- Import flag: input → output
$ go generate ./example
$ go run ./example
Please refer to the following if you like this package and generating more.
- go-gen-lo: Generate samber/lo method for your struct.