尝试使用go1.18泛型进行入门级实践?
- 内容介绍
- 文章标签
- 相关推荐
本文共计677个文字,预计阅读时间需要3分钟。
今天,Golang终于发布了1.18版本,这个版本最大的变化就是增加了泛型。虽然beta版本中没有尝试泛型,但鉴于在其他语言的泛型经验,上手泛型并非难事。官方示例:Tutoria。
今天golang终于发布了1.18版本,这个版本最大的一个改变就是加入了泛型。虽然没有在beta版本的时候尝试泛型,但是由于在其他语言的泛型经验,入手泛型不是件难事~
官方示例Tutorial: Getting started with generics - The Go Programming Language
根据官方示例可以看出,在go中泛型声明使用中括号,大体用法也与其他语言差不多。下面就官方示例中出现的几个点做记录。
comparable在泛型的约束中有 comparable 关键字,我们进到源码中看到解释:
// comparable is an interface that is implemented by all comparable types
// (booleans, numbers, strings, pointers, channels, arrays of comparable types,
// structs whose fields are all comparable types).
// The comparable interface may only be used as a type parameter constraint,
// not as the type of a variable.
type comparable interface{ comparable }
看得出来这是官方定义的一个可比较的类型的一个泛型约束,它也只能存在于类型参数约束的时候。
一些改变我们尝试修改官方示例,体验一下其他的关键词及相关用法。
本文共计677个文字,预计阅读时间需要3分钟。
今天,Golang终于发布了1.18版本,这个版本最大的变化就是增加了泛型。虽然beta版本中没有尝试泛型,但鉴于在其他语言的泛型经验,上手泛型并非难事。官方示例:Tutoria。
今天golang终于发布了1.18版本,这个版本最大的一个改变就是加入了泛型。虽然没有在beta版本的时候尝试泛型,但是由于在其他语言的泛型经验,入手泛型不是件难事~
官方示例Tutorial: Getting started with generics - The Go Programming Language
根据官方示例可以看出,在go中泛型声明使用中括号,大体用法也与其他语言差不多。下面就官方示例中出现的几个点做记录。
comparable在泛型的约束中有 comparable 关键字,我们进到源码中看到解释:
// comparable is an interface that is implemented by all comparable types
// (booleans, numbers, strings, pointers, channels, arrays of comparable types,
// structs whose fields are all comparable types).
// The comparable interface may only be used as a type parameter constraint,
// not as the type of a variable.
type comparable interface{ comparable }
看得出来这是官方定义的一个可比较的类型的一个泛型约束,它也只能存在于类型参数约束的时候。
一些改变我们尝试修改官方示例,体验一下其他的关键词及相关用法。

