Skip to content

snamiki1212/go-gen-slice-accessors

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

76 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

go-gen-slice-accessors

Generate accessors for each field in the slice struct.

  • Easy Setup & Removal
  • Zero Package Size, Code Genration

Usage

1. Install binary

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

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 and got generated code.

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

Help

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

E2E

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

LICENSE

MIT