How do go's len() and make() functions work?

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

How do go's len() and make() functions work?

问题

Go语言中的len()make()函数是如何工作的?由于该语言不支持泛型和函数重载,我不明白如何实现func len(v Type) intfunc 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

lenmake函数是语言规范的一部分,并内置于编译器中。内置函数的运行时支持在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.

huangapple
  • 本文由 发表于 2015年1月29日 08:07:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/28204831.html
匿名

发表评论

匿名网友

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

确定