I’m trying to implement basic list operations without using inbuilt methods such as len(). But i couldn’t find a way to get slice/array size in bytes, to implement length() function.
I have tried unsafe.Sizeof() method, but as for the documentation it only gives size of the slice descriptor, not the size of the memory referenced by the slice.
type IntList []int
func main() {
list := IntList{1, 2, 3, 4}
list.Length() // expected result - 4
}
// assuming int type contains 4 bytes
func (l IntList) Length() int {
size := actualByteSize(l) / 4
return int(size)
}
No, length of an integer array, as i mentioned at my sample code.
list := IntList{1, 2, 3, 4}
list.Length() // expected result - 4
I want to get byte size of this array without knowing number of elements in that particular array. Actual i just want to re-implement inbuilt len() method (Sounds stupid but i just want to give a shot)
So getting the length without using len() could be done like this:
package main
import (
"fmt"
"unsafe"
)
type slice struct {
ptr uintptr
len int
cap int
}
func main() {
someSlice := make([]byte, 666)
fmt.Println((*slice)(unsafe.Pointer(&someSlice)).len)
}