Nan Xiao
Nan Xiao

Reputation: 17477

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

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

Upvotes: 3

Views: 201

Answers (1)

nemo
nemo

Reputation: 57659

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.

Upvotes: 4

Related Questions