有没有方便的方法来初始化一个字节数组?
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
最佳答案
您可以将字符串复制到字节数组的 slice 中:
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)
}
编辑:根据 jimt 的建议,使用 T1 文字的命名形式。
关于go - 在 Go 中将字符串转换为固定大小的字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8039245/