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

标签 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

最佳答案

您可以将字符串复制到字节数组的 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/

相关文章:

function - Golang - 为什么我可以从值类型调用指针接收器方法?

linux - 使用Go生成适用于`/etc/shadow`的哈希密码字符串

JSON 有时是数组有时是对象

go - 为什么 bcrypt 库 CompareHashAndPassword 方法很慢?

html - 资源解释为图像但使用 MIME 类型 text/html appengine go 传输

go - 这是在golang中的类型转换吗?

json - Golang JSON Unmarshal 序列号

http - 所有独立任务都应该在 http 请求 goroutine 之外处理吗?

debugging - go http 服务器和 fasthttp 中的内存泄漏

json - 根据参数值在 Golang 中解码传入的 JSON