Generate accessors for each field in the slice struct.
- Easy Setup & Removal
- Zero Package Size, Code Genration
$ 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`
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
+// 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
+}
Tip
Install a binary using go:generate
and your team will not need to think about the installation 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 target entity name
-x, --exclude strings field names to exclude
-h, --help help for gen-slice-accessors
-i, --input string input file name
-o, --output string output file name
-r, --rename strings rename accessor name / e.g. --rename=Name:GetName
-s, --slice string target slice name
- Common case (src / generated code)
- Exclude accessors (src / generated code)
- Rename accessors (src / generated code)
- Private accessors (src / generated code)
$ go generate ./example
$ go run ./example