Go内置函数使用泛型吗?

huangapple go评论74阅读模式
英文:

Do Go built-ins use generics?

问题

在查看Go的内置函数时,我意识到它们不使用接口,而是使用了一个名为"Type"的魔法函数。

https://golang.org/src/builtin/builtin.go

那么,如果不使用泛型,如何实现这种功能呢?如果我想编写一个类似于append函数的函数(接受任意类型的数组),该如何实现而不使用接口呢?

英文:

Looking at the builtins function of Go, I just realize that they don't use interfaces and instead use a magic 'Type'.

https://golang.org/src/builtin/builtin.go

So how exactly is this possible without using generics ? How would I write a function with a signature similar to append's (that takes an array of any type) without interfaces ?

答案1

得分: 5

你无法创建具有这种通用、神奇的“基因”的函数。具有这种特性的函数是由语言规范覆盖的内置函数,在预声明标识符部分列出。

引用自Effective Go: Append:

append的签名是这样的:[...] 简而言之,它是这样的:

func append(slice []T, elements ...T) []T

其中的 T 是任何给定类型的占位符。你无法在Go中编写一个函数,其中类型 T 是由调用者确定的。这就是为什么 append 是内置的:它需要编译器的支持。

相关问题请参考:

https://stackoverflow.com/questions/39073756/go-functions-accessed-through-variables/39073811#39073811

https://stackoverflow.com/questions/28487036/return-map-like-ok-in-golang-on-normal-functions/28487270#28487270

英文:

It is not possible for you to create such functions. Functions that have this generic, magic "gene" are builtin functions covered by the language specification, listed in section Predeclared identifiers.

Quoting from Effective Go: Append:

> The signature of append [...] schematically, it's like this:
>
> func append(slice []T, elements ...T) []T
>
> where T is a placeholder for any given type. You can't actually write a function in Go where the type T is determined by the caller. That's why append is built in: it needs support from the compiler.

See related questions:

https://stackoverflow.com/questions/39073756/go-functions-accessed-through-variables/39073811#39073811

https://stackoverflow.com/questions/28487036/return-map-like-ok-in-golang-on-normal-functions/28487270#28487270

huangapple
  • 本文由 发表于 2017年6月15日 20:37:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/44567728.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定