gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 13:02:20 30 4
gpt4 key购买 nike

有没有方便的方法来初始化一个字节数组?

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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com