gpt4 book ai didi

go - 在 map golang 中使用不同的结构作为值

转载 作者:IT王子 更新时间:2023-10-29 02:20:08 27 4
gpt4 key购买 nike

有没有办法创建一个映射到多个结构中,然后使用它?

我有几个不同的结构,它们实现相同的接口(interface)并为每个结构匹配输入类型。

我想从不同的输入中读取数据到结构中——在编译时不知道输入类型。

type myInput struct {
InputType string
data []bytes
}

// Will get as an input after compeleation
inputs := []myInput{
myInput{InputType: "a", data: []bytes{0x01, 0x02, 0x03}},
myInput{InputType: "b", data: []bytes{0x01, 0x02}},
}

type StructA struct {
A uint16
B uint32
}

func (a StructA) name () {
fmt.Printf("name is: %d %d", a.A, a.B)
}

type StructB struct {
C uint32
}

func (b StructB) name () {
fmt.Printf("name is: %d", b.C)
}

AorB map[string]<???> {
"a": StructA,
"b": StructB,
}

此时,我不知道该怎么办。我需要根据输入类型获取正确的结构,并使用 binary.Read 初始化该结构。

for _, myInput := range (inputs) {
// ???? :(
myStruct := AtoB[myInput.InputType]{}
reader :=bytes.NewReader(input1)
err := binary.Read(reader, binary.BigEndian, &myStruct)
fmt.Printf(myStruct.name())
}

谢谢!

最佳答案

定义接口(interface)

type Bin interface {
name() string
set([]byte) // maybe returning error
}

您将只处理 Bin

type StructA struct { /* your code so far */ }
type StructB struct { /* your code so far */ }

func (a *StructA) set(b []byte) {
a.A = b[0]<<8 + b[1] // get that right, too lazy to code this for you
a.B = b[2]<<24 + b[3]<<16 + ...
}
// same for StructB

所以你的 StructA/B 现在是 Bins。

func makeBin(in myInput) Bin {
var bin Bin
if in.InputType == "a" {
bin = &StructA{}
} else {
bin = &StructB{}
}
bin.set(in.data) // error handling?
return bin
}

如果您有两种以上的类型:如果 if 或创建一个微型类型注册表(反射),则使用开关代替。

关于go - 在 map golang 中使用不同的结构作为值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53204138/

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