英文:
How do go's len() and make() functions work?
问题
Go语言中的len()和make()函数是如何工作的?由于该语言不支持泛型和函数重载,我不明白如何实现func len(v Type) int和func make(Type, size IntegerType) Type这两个函数。
我在Go的源代码中找不到这个函数,我找到的最接近的是这个链接。
英文:
How do go's len() and make() functions work? Since the language lacks support for both generics and function overloading I don't see how func len(v Type) int is possible. The same goes for func make(Type, size IntegerType) Type.
I can't seem to find the function in the go source, the closest I've managed to find is this
答案1
得分: 18
len和make函数是语言规范的一部分,并内置于编译器中。内置函数的运行时支持在runtime包中。
文件builtin.go仅用于文档目的,不会被编译。
英文:
The len and make functions are part of the language specification and built-in to the compiler. Runtime support for built-in functions is in the runtime package.
The file builtin.go is used for documentation only. It's not compiled.
答案2
得分: 1
由于Go语言的严格类型,编译器总是知道你传递给len函数的类型,因此它会根据不同的类型调用不同的函数,这在编译时可以确定。在大多数情况下,你试图获取切片的长度,此时len函数只需要返回该切片结构体的len字段(因为切片实际上是一个结构体);字符串也是同样的道理。
编译器有各种各样的技巧,由编译器生成的汇编代码很少遵循你输入的完全相同的逻辑。
英文:
Because of Go's strict types, the compiler always knows what type you are passing to the len function and so it goes to a different function for different types, which can be determined at compile-time. In most cases you are attempting to get the length of a slice, in which case the len function only need return the len field for that slice's struct (since a slice is really a struct); same for a string.
Compilers have all kinds of tricks, the assembly code generated by the compiler rarely follows the exact same logic you typed.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论