Created
May 17, 2022 14:18
-
-
Save naoki-sawada/d82b924bd26f21603d480fe7fa5ace08 to your computer and use it in GitHub Desktop.
Go generics example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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