How to get actual byte size of array/slice in Go

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)
}

I’m new to Go. :blush:

It could be the same as:

func (list *IntList) Length() int {
	return len(*list)
}

I want to do it without using relevant inbuilt methods, as i know normal approach is

byteSize(intArray) / size_of_int

I was wondering is there any way to achieve this in Go.

Thanks! but as i mentioned i want to get the length of array without using inbuilt length function.

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 :smile: but i just want to give a shot)

In that case you can use package encoding/binary and Size function, for example
https://play.golang.org/p/HhJif66VwY

A slice is really a struct like this

struct {
   address to array
   len int
   cap int
}

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)

}

1 Like

It seems your asnwer did not arrive complete. Please, send it again …
In the meantime, you can check https://blog.golang.org/go-slices-usage-and-internals

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.