gpt4 book ai didi

go - 如何在 Reflect.FieldByName() 中读取 slice

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

我将数据传递给具有输入类型接口(interface)的函数。

这段代码:

main(){
SampleData := Input{
Recipients: []string{"abc","efg"},
Msg: string("Test message"),
}
InsertInSendTBL(SampleData)
}

type Input struct {
Recipients []string
Msg string
sender string
}
type Output struct {
Recipients []string
Msg string
reciver string
}
func InsertInSendTBL(Data interface{}) {
DataInput := reflect.ValueOf(Data)
NewVal := Output{
Recipients: DataInput.FieldByName("Recipients").([]string{}),//LINE ERORE
Msg: DataInput.FieldByName("Msg").String(),
sender: "1000",
}
}

我的结构字段之一是字符串 slice 。我在 reflect 包中搜索但没有找到任何东西,所以我使用 ".([]string{})"。结果是这个错误:

invalid type assertion: DataInput.FieldByName("Recipients").(composite literal) (non-interface type reflect.Value on left)

所以我在 reflect 中尝试接口(interface)但是另一个错误

cannot use DataInput.FieldByName("Recipients").Interface() (type interface {}) as type []string in field value: need type assertion

最佳答案

你需要结合你的两次尝试:

sliceOfString, ok := DataInput.FieldByName("Recipients").Interface().([]string)
if !ok {
panic("Not a []string!")
}

关于go - 如何在 Reflect.FieldByName() 中读取 slice ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50325136/

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