初始字节数组有方便的方法吗?
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)