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 怎么改成输入一个要删除的数后现实剩余的数再输入一个删除的数再现实剩余的数用yes表示继续no结束程序
  • ¥15 在启动roslaunch时出现如下问题
  • ¥15 汇编语言实现加减法计算器的功能
  • ¥20 关于多单片机模块化的一些问题
  • ¥30 seata使用出现报错,其他服务找不到seata
  • ¥35 引用csv数据文件(4列1800行),通过高斯-赛德尔法拟合曲线,在选取(每五十点取1点)数据,求该数据点的曲率中心。
  • ¥20 程序只发送0X01,串口助手显示不正确,配置看了没有问题115200-8-1-no,如何解决?
  • ¥15 Google speech command 数据集获取
  • ¥15 vue3+element-plus页面崩溃
  • ¥15 像这种代码要怎么跑起来?