search.png
关于我
menu.png
go1.18泛型初体验

go在1.18正式推出了泛型,你是否和博主一样好奇其语法呢?快啊来看看吧

1. 版本更新&插件更新

go如何更新到最新版本,可以查看https://www.hengyumo.cn/momoblog/detail/20220417102155

idea插件更新:
setting >> plugin >> installed


全部更新之后

idea版本更新(可能要更新多次,直到更新到不能更新为止):
help >> check update

在此处勾选上泛型支持

可以看到,现在使用泛型已经不会报语法错误了:

2. 基础语法

package test_genericity

import (
    "fmt"
)

func MyPrintln[C any](a C) {
    fmt.Println(a)
}

func Example_g1() {
    MyPrintln(1)
    MyPrintln("小王")
    MyPrintln([]int{3, 2, 1})
    //Output:
    //1
    //小王
    //[3 2 1]
}


any代表任意类型,等于interface{}

func min[T ~int | ~float64](x, y T) T {
    if x > y {
        return y
    } else {
        return x
    }
}

func Example_g2() {
    //f := min                   // illegal: min must be instantiated with type arguments when used without being called
    minInt := min[int] // minInt has type func(x, y int) int
    a := minInt(2, 3)  // a has value 2 of type int
    fmt.Println(a)
    b := min[float64](2.0, 3) // b has value 2.0 of type float64
    fmt.Println(b)
    c := min(b, -1) // c has value -1.0 of type float64
    fmt.Println(c)
    //d := min(1, 0.5) // 语法错误,default type float64 of 0.5 does not match inferred type int for T
    // Output:
    // 2
    // 2
    // -1
}

上例演示了使用~int | ~float64作为泛型约束,实现了一个可以通用比较int或者float64的min函数。

版权声明

知识共享许可协议 本文章由作者“衡于墨”创作,转载请注明出处,未经允许禁止用于商业用途

本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可。
发布时间:2022年04月17日 10:39:27

评论区#

还没有评论哦,期待您的评论!

关闭特效