首页 > 其他分享 >0095-Go-泛型

0095-Go-泛型

时间:2022-10-30 08:33:12浏览次数:77  
标签:head lst element 泛型 tail func Go 0095

环境

  • Time 2022-08-24
  • Go 1.19

前言

说明

参考:https://gobyexample.com/generics

目标

使用 Go 语言的泛型。

泛型函数

package main

import "fmt"

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
}

func main() {
    var m = map[int]string{1: "2", 2: "4", 4: "8"}

    fmt.Println("keys m:", MapKeys(m))
}

定义链表

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
}

使用

func main() {

    lst := List[int]{}
    lst.Push(10)
    lst.Push(13)
    lst.Push(23)
    fmt.Println("list:", lst.GetAll())
}

总结

使用 Go 语言的泛型。

附录

标签:head,lst,element,泛型,tail,func,Go,0095
From: https://www.cnblogs.com/jiangbo4444/p/16840467.html

相关文章

  • 0075-Go-变量
    环境Time2022-08-23Go1.19前言说明参考:https://gobyexample.com/variables目标使用Go语言变量的申明和使用变量。示例packagemainimport"fmt"funcma......
  • 0076-Go-常量
    环境Time2022-08-23Go1.19前言说明参考:https://gobyexample.com/constants目标使用Go语言的常量。示例packagemainimport("fmt""math")co......
  • 0077-Go-for 循环
    环境Time2022-08-23Go1.19前言说明参考:https://gobyexample.com/for目标使用Go语言的for循环。单条件循环类似其它语言中的while循环。packagemain......
  • 0078-Go-if else 条件判断
    环境Time2022-08-23Go1.19前言说明参考:https://gobyexample.com/if-else目标使用Go语言的if/else条件判断。条件判断条件判断的小括号可以省略,但是后面的......
  • 0079-Go-switch 分支
    环境Time2022-08-23Go1.19前言说明参考:https://gobyexample.com/switch目标使用Go语言的switch分支语句。整数分支packagemainimport"fmt"funcmai......
  • 0080-Go-数组
    环境Time2022-08-23Go1.19前言说明参考:https://gobyexample.com/arrays目标使用Go语言的数组。申明数组packagemainimport"fmt"funcmain(){v......
  • 0081-Go-切片 slice
    环境Time2022-08-23Go1.19前言说明参考:https://gobyexample.com/slices目标使用Go语言的切片类型。新建切片类型packagemainimport"fmt"funcmain()......
  • 0082-Go-关联类型 map
    环境Time2022-08-23Go1.19前言说明参考:https://gobyexample.com/maps目标使用Go语言的关联类型map。新建mappackagemainimport"fmt"funcmain(){......
  • 0073-Go-hello world
    环境Time2022-08-23Go1.19前言说明参考:https://gobyexample.com/hello-world目标使用Go语言打印helloworld。初始化项目gomodinitjiangbo/go打印hel......
  • 0074-Go-值类型
    环境Time2022-08-23Go1.19前言说明参考:https://gobyexample.com/values目标使用Go语言的字符串,整型,浮点型和布尔类型。示例packagemainimport"fmt"fu......