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

如何修复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?

你好,我试图用常量制作字节切片,但我得到常量x溢出字节 代码>错误。 这是我的常量: p>

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

这是我声明切片的方式: p>

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

每次构建时,我都会得到常数266溢出字节。 我应该如何声明我的常量以解决此问题? p> div>

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.