Simple Singly-Linked-List in Go1.18 with Generics
本当はList構造には comparable だけじゃなくてordered みたいなものを定義して, sort可能にしたい,というmotivationもあるけど,現状 comparable | customInterface みたいなtype unionはできないっぽい?
でもこの状態ですでにlistから特定の要素を探索したりremoveするcodeはかける.Go Generics, 非常に楽しい.
code:go
package main
import "fmt"
type nodeV comparable struct {
next *nodeV
value V
}
type listV comparable struct {
head *nodeV
length int
}
func main() {
l1 := initList([]int{1, 2, 3, 4, 5})
fmt.Printf("l1 length: %d\n", l1.length)
for cur := l1.head; cur != nil; cur = cur.next {
fmt.Printf("%+v\n", cur.value)
}
fmt.Printf("l1.exist(4): %v\n", l1.exist(4))
fmt.Printf("l1.exist(100): %v\n", l1.exist(100))
l2 := initList([]string{"foo", "bar", "baz"})
fmt.Printf("l2 length: %d\n", l2.length)
for cur := l2.head; cur != nil; cur = cur.next {
fmt.Printf("%+v\n", cur.value)
}
fmt.Printf("l2.exist(\"foo\"): %v\n", l2.exist("foo"))
fmt.Printf("l2.exist(\"Drumato\"): %v\n", l2.exist("Drumato"))
}
func initListV comparable(values []V) *listV {
if len(values) == 0 {
return &listV{head: nil, length: 0}
}
head := &nodeV{value: values0}
cur := head
for _, v := range values1: {
next := &nodeV{value: v}
cur.next = next
cur = cur.next
}
return &listV{head: head, length: len(values)}
}
func (l *listcomparable) exist(target comparable) bool {
for cur := l.head; cur != nil; cur = cur.next {
if cur.value == target {
return true
}
}
return false
}
Links
https://go.dev/doc/tutorial/generics