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

时间:2011-11-07 16:16:00

标签: 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)
}

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

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

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

2 个答案:

答案 0 :(得分:13)

你需要一个字节数组吗?在Go中,您最好使用字节切片。

package main
import "fmt"

type T1 struct {
   f1 []byte
   f2 int
}

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

答案 1 :(得分:13)

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

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)
}

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