Created
March 17, 2024 11:35
-
-
Save ponkotuy/6e0a3c4999234b93a0931a17afaea6f2 to your computer and use it in GitHub Desktop.
Golang Genericsサンプル(単方向リスト)
This file contains hidden or 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" | |
"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