Reading about arrays and slices in Golang.
Why built-in functions like len
and cap
are used and not similar methods on slice objects?
if cap(slice) == len(slice) {
fmt.Println("slice is full!")
}
vs
if slice.cap() == slice.len() {
fmt.Println("slice is full!")
}
Why polluting the global namespace? Why not using object oriented style?
Also, do such methods exist and can they be used instead of built-in functions?
There is a FAQ entry on this, but here is my take:
len()
and cap()
are built in functions because they are understood by the compiler. You can't make your own replacements - they are very much part of the core language in a way that methods aren't, and you shouldn't confuse them with methods.
In Go a slice is made of three things, a length, a capacity and a pointer to the underlying memory. Eg the definition from reflect
type SliceHeader struct {
Data uintptr
Len int
Cap int
}
All len(x)
does is read the length from the slice structure, so it is shorthand for something like x.Len
and the compiler understands that and optimises it accordingly.