gpt4 book ai didi

reflection - 高语 : Reading and casting bytes into struct fields

转载 作者:IT王子 更新时间:2023-10-29 01:43:10 28 4
gpt4 key购买 nike

我正在从 io.Reader 逐字段读取到结构中。

// structFields returns a sequence of reflect.Value
for field := range structFields {
switch field.Kind() {
case reflect.String:
// Omitted
case reflect.Uint8:
value := make([]byte, 2)
reader.Read(value)

var num uint8
err := binary.Read(bytes.NewBuffer(value[:]), binary.LittleEndian, &num)
if err != nil { return err }
field.SetUint(int64(num))
// Case statements for each of the other uint and int types omitted
}
}

不幸的是,需要为每种 Uint 和 Int 数据类型重复 reflect.Uint8 的 block ,因为我需要在每种情况下正确创建 var num

有什么方法可以简化这个 switch 语句吗?

最佳答案

不使用 var num uint8field.SetUint(int64(num)) 只需将指向结构字段的指针传递给 binary.Read:

ptr := field.Addr().Interface()
err := binary.Read(bytes.NewBuffer(value[:]), binary.LittleEndian, ptr)

然后让案例陈述说:

case reflect.Uint8, reflect.Int, reflect.Uint, ...:

然后您需要处理不同大小的数字。幸运的是,您可以将阅读器直接传递给 binary.Read,它会处理它:

err := binary.Read(reader, binary.LittleEndian, ptr)

最后,正如 FUZxxl 所说,您只需将指向整个结构的指针传递给 binary.Read,它就会为您完成所有这些工作。

关于reflection - 高语 : Reading and casting bytes into struct fields,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24898304/

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