Skip to content

snamiki1212/go-gen-slice-accessors

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

88 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

go-gen-slice-accessors

Generate accessors for each field in the slice struct.

  • Easy Setup & Removal
  • Code Generation & Zero Package Size

Usage

1. Install go-gen-sllice-accessors

$ 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`

2. Add go:generate directive.

// 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

3. Run go generate command.

$ 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
+}

4. Enjoy programming.

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 {
    ...

Help

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

Examples

Contribution

E2E

$ go generate ./example
$ go run ./example

Alternatives

Please refer to the following if you like this package and generating more.

  • go-gen-lo: Generate samber/lo method for your struct.

LICENSE

MIT