9
votes

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

2

2 Answers

17
votes

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
votes

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.