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.

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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度