英文:
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
你无法创建具有这种通用、神奇的“基因”的函数。具有这种特性的函数是由语言规范覆盖的内置函数,在预声明标识符部分列出。
append
的签名是这样的:[...] 简而言之,它是这样的:func append(slice []T, elements ...T) []T
其中的
T
是任何给定类型的占位符。你无法在Go中编写一个函数,其中类型T
是由调用者确定的。这就是为什么append
是内置的:它需要编译器的支持。
相关问题请参考:
英文:
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:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论