duanmengsuo9302 2019-03-25 12:23
浏览 163
已采纳

如何修复Go中的“常量x oveflows字节”错误?

Hello I am trying to make a byte slice with constants but I get the constant x overflows byte error. Here are my constants:

const(
     Starttrame1 = 0x10A
     Starttrame2 = 0x10B
     Starttrame3 = 0X10C
     Starttrame4 = 0X10D
     Starttrame5 = 0X10E
     Starttrame6 = 0x10F
)

and here is how I declare my slice:

var startValues = [6]byte{Starttrame1,Starttrame2,Startrame3,Starttrame4,Starttrame5,Starttrame6}

Everytime I build I get the constant 266 overflows byte. How should I declare my constants in order to fix this?

  • 写回答

1条回答 默认 最新

  • douqin6785 2019-03-25 12:26
    关注

    In Go, byte is an alias for uint8, which is the set of all unsigned 8-bit integers (0..255, both inclusive), see Spec: Numeric types. Which means a value of 0x10A = 266 cannot be stored in a value of type byte.

    If you need to store those constants, use a different type, e.g. uint16:

    const (
        Starttrame1 = 0x10A
        Starttrame2 = 0x10B
        Starttrame3 = 0X10C
        Starttrame4 = 0X10D
        Starttrame5 = 0X10E
        Starttrame6 = 0x10F
    )
    
    var data = [...]uint16{
        Starttrame1, Starttrame2, Starttrame3, Starttrame4, Starttrame5, Starttrame6,
    }
    

    Try it on the Go Playground.

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

报告相同问题?

悬赏问题

  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?