Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the binary.Size() return (-1)?

Tags:

go

The code snippet likes this:

package main
import (
    "fmt"
    "encoding/binary"
    "reflect"
)

const (
    commandLen = 1
    bufLen int = 4
)

func main(){
    fmt.Printf("%v %v\n", reflect.TypeOf(commandLen), reflect.TypeOf(bufLen))
    fmt.Printf("%d %d", binary.Size(commandLen), binary.Size(bufLen))
}

And the output is:

int int
-1 -1

I think since the types of commandLen and bufLen are int, and from "Programming in golang", the int should be int32 or int64 which depending on the implementation, so I think the binary.Size() should return a value, not (-1).

Why the binary.Size() return (-1)?

like image 701
Nan Xiao Avatar asked Feb 27 '26 06:02

Nan Xiao


1 Answers

tl;dr

int is not a fixed-length type, so it won't work. Use something that has a fixed length, for example int32.

Explanation

This might look like a bug but it is actually not a bug. The documentation of Size() says:

Size returns how many bytes Write would generate to encode the value v, which must be a
fixed-size value or a slice of fixed-size values, or a pointer to such data.

A fixed-size value is a value that is not dependent on the architecture and the size is known beforehand. This is the case for int32 or int64 but not for int as it depends on the environment's architecture. See the documentation of int.

If you're asking yourself why Size() enforces this, consider encoding an int on your 64 bit machine and decoding the data on a remote 32 bit machine. This is only possible if you have length encoded types, which int is not. So you either have to store the size along with the type or enforce fixed-length types which the developers did.

This is reflected in the sizeof() function of encoding/binary that computes the size:

case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
       reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
       reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128:
       return int(t.Size()), nil

As you can see, there are all number types listed but reflect.Int.

like image 80
nemo Avatar answered Feb 28 '26 19:02

nemo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!