Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

function

types

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

like image 392
Jay Crumb Avatar asked Jan 29 '15 00:01

Jay Crumb


2 Answers

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.

like image 58
Bayta Darell Avatar answered Oct 03 '22 08:10

Bayta Darell


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.

like image 20
Alasdair Avatar answered Oct 03 '22 07:10

Alasdair