Skip to content

Instantly share code, notes, and snippets.

@naoki-sawada
Created May 17, 2022 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save naoki-sawada/d82b924bd26f21603d480fe7fa5ace08 to your computer and use it in GitHub Desktop.
Save naoki-sawada/d82b924bd26f21603d480fe7fa5ace08 to your computer and use it in GitHub Desktop.
Go generics example
package main
import "fmt"
type Base interface {
getID() int64
}
type Person struct {
ID int64
Name string
Age uint
}
func (p Person) getID() int64 {
return p.ID
}
type Vehicle struct {
ID int64
Name string
}
func (v Vehicle) getID() int64 {
return v.ID
}
func idList[K Base](xs []K) []int64 {
ids := make([]int64, len(xs))
for i, x := range xs {
ids[i] = x.getID()
}
return ids
}
func main() {
ps := make([]Person, 2)
ps[0] = Person{100, "piyo", 10}
ps[1] = Person{101, "huga", 30}
vs := make([]Vehicle, 2)
vs[0] = Vehicle{1, "ssss"}
vs[1] = Vehicle{2, "iiii"}
pids := idList(ps)
fmt.Println(pids)
vids := idList(vs)
fmt.Println(vids)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment