在Go中将字符串转换为固定大小的字节数组

Dan*_*Lin 23 go

初始字节数组有方便的方法吗?

package main
import "fmt"
type T1 struct {
  f1 [5]byte  // I use fixed size here for file format or network packet format.
  f2 int32
}
func main() {
  t := T1{"abcde", 3}
  // t:= T1{[5]byte{'a','b','c','d','e'}, 3} // work, but ugly
  fmt.Println(t)
}
Run Code Online (Sandbox Code Playgroud)

prog.go:8:不能在字段值中使用"abcde"(类型字符串)作为类型[5] uint8

如果我改变行 t := T1{[5]byte("abcde"), 3}

prog.go:8:无法将"abcde"(类型字符串)转换为类型[5] uint8

Ste*_*ark 14

您可以将字符串复制到字节数组的切片中:

package main
import "fmt"
type T1 struct {
  f1 [5]byte
  f2 int
}
func main() {
  t := T1{f2: 3}
  copy(t.f1[:], "abcde")
  fmt.Println(t)
}
Run Code Online (Sandbox Code Playgroud)

编辑:使用命名形式的T1文字,按照jimt的建议.


jim*_*imt 13

你需要一个字节数组有什么特别的原因吗?在Go中,您最好使用字节切片.

package main
import "fmt"

type T1 struct {
   f1 []byte
   f2 int
}

func main() {
  t := T1{[]byte("abcde"), 3}
  fmt.Println(t)
}
Run Code Online (Sandbox Code Playgroud)

  • 我需要字节数组来进行网络数据包传输,将我的数据保存到文件中. (3认同)
  • @ JayD3e这不是正确答案,因为我需要FIXED字节数组而不是字节片. (3认同)
  • 如果你想这样做,你也应该使用固定大小的int(int32,int64). (2认同)