Type converting slices of interfaces

后端 未结 6 1741
孤街浪徒
孤街浪徒 2020-11-22 04:04

I\'m curious why Go does\'t implicitly convert []T to []interface{} when it will implicitly convert T to interface{}. Is

6条回答
  •  不要未来只要你来
    2020-11-22 04:58

    In case you need more shorting your code, you can creating new type for helper

    type Strings []string
    
    func (ss Strings) ToInterfaceSlice() []interface{} {
        iface := make([]interface{}, len(ss))
        for i := range ss {
            iface[i] = ss[i]
        }
        return iface
    }
    

    then

    a := []strings{"a", "b", "c", "d"}
    sliceIFace := Strings(a).ToInterfaceSlice()
    

提交回复
热议问题