Skip to content

Instantly share code, notes, and snippets.

@ponkotuy
Created March 17, 2024 11:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ponkotuy/6e0a3c4999234b93a0931a17afaea6f2 to your computer and use it in GitHub Desktop.
Save ponkotuy/6e0a3c4999234b93a0931a17afaea6f2 to your computer and use it in GitHub Desktop.
Golang Genericsサンプル(単方向リスト)
package main
import (
"fmt"
"golang.org/x/exp/constraints"
)
type List[T any] struct {
head *T
tail *List[T]
}
func NIL[T any]() *List[T] {
return &List[T]{nil, nil}
}
func isNil[T any](xs *List[T]) bool {
return xs.head == nil
}
func genList[T any](xs ...T) *List[T] {
if len(xs) == 0 {
return NIL[T]()
}
return &List[T]{&xs[0], genList(xs[1:]...)}
}
func sum[T constraints.Integer](xs *List[T]) T {
if isNil(xs) {
return 0
}
return *xs.head + sum(xs.tail)
}
func main() {
list := genList(1, 2, 3)
sumList := sum(list)
fmt.Printf("%d", sumList)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment