doudi8525 2013-10-25 01:50
浏览 158
已采纳

为什么binary.Size()返回(-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
", 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)?

  • 写回答

1条回答 默认 最新

  • douxiyi2418 2013-10-25 02:02
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来