dongyongan9941 2018-05-14 07:33
浏览 239
已采纳

如何在Reflect.FieldByName()中读取切片

I pass data to a func with input type interface.

This code:

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",
    }
}

One of my struct fields is slice of string. I searched in reflect package but not found anything so I use ".([]string{})" . Result is this error:

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

so I try interface in reflect But another error

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

  • 写回答

1条回答 默认 最新

  • douzhulan1815 2018-05-14 07:34
    关注

    You need to combine your two attempts:

    sliceOfString, ok := DataInput.FieldByName("Recipients").Interface().([]string)
    if !ok {
        panic("Not a []string!")
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 vb net 使用 sendMessage 如何输入鼠标坐标
  • ¥200 求能开发抖音自动回复卡片的软件
  • ¥15 关于freesurfer使用freeview可视化的问题
  • ¥100 谁能在荣耀自带系统MagicOS版本下,隐藏手机桌面图标?
  • ¥15 求SC-LIWC词典!
  • ¥20 有关esp8266连接阿里云
  • ¥15 C# 调用Bartender打印机打印
  • ¥15 我这个代码哪里有问题 acm 平台上显示错误 90%,我自己运行好像没什么问题
  • ¥50 C#编程中使用printDocument类实现文字排版打印问题
  • ¥15 找会编程的帅哥美女 可以用MATLAB里面的simulink编程,用Keil5编也可以。