Generics

  • Go 1.18버전뢀터 genericsλ₯Ό μ§€μ›ν•œλ‹€.

func MapKeys[K comparable, V any](m map[K]V) []K {
    r := make([]K, 0, len(m))
    for k := range m {
        r = append(r, k)
    }
    return r
}
  • MapKeys takes a map of any type and returns a slices of its keys

func main() {
    var m = map[int]string{1: "2", 2: "4", 4: "8"}
    fmt.Println("keys:", MapKeys(m))
}
  • μ΄λ ‡κ²Œ νƒ€μž… 상관없이 keyκ°’λ§Œ λ°˜ν™˜ν•˜λŠ” ν•¨μˆ˜λ₯Ό λ§Œλ“€ 수 μžˆλ‹€.

//단일 μ—°κ²°λ¦¬μŠ€νŠΈμ— λŒ€ν•œ μ˜ˆμ‹œμ΄λ‹€.
type List[T any] struct {
    head, tail *element[T]
}

type element[T any] struct {
    next *element[T]
    val T
}

func (lst *List[T]) Push(v T) {
    if lst.tail == nil {
        lst.head = &element[T]{val: v}
        lst.tail = lst.head
    } else {
        lst.tail.next = &element[T]{val: v}
        lst.tail = lst.tail.next
    }
}

func (lst *List[T]) GetAll() []T {
    var elems []T
    for e := lst.head; e != nil; e = e.next {
        elems = append(elems, e.val)
    }
    return elems
}

Last updated