有没有方便的方法来初始化一个字节数组?
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“(类型字符串)作为类型5uint8
如果我将行更改为t := T1{[5]byte("abcde"), 3}
prog.go:8:无法将"abcde“(字符串类型)转换为5uint8类型
发布于 2011-11-08 12:21:40
您可以将字符串复制到字节数组的片段中:
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文字的命名形式。
发布于 2011-11-08 00:41:24
你需要字节数组有什么特殊的原因吗?在Go中,使用字节片会更好。
package main
import "fmt"
type T1 struct {
f1 []byte
f2 int
}
func main() {
t := T1{[]byte("abcde"), 3}
fmt.Println(t)
}https://stackoverflow.com/questions/8039245
复制相似问题