简体   繁体   中英

How to read slice in 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

You need to combine your two attempts:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM