Type converting slices of interfaces

后端 未结 6 1748
孤街浪徒
孤街浪徒 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:54

    In Go, there is a general rule that syntax should not hide complex/costly operations. Converting a string to an interface{} is done in O(1) time. Converting a []string to an interface{} is also done in O(1) time since a slice is still one value. However, converting a []string to an []interface{} is O(n) time because each element of the slice must be converted to an interface{}.

    The one exception to this rule is converting strings. When converting a string to and from a []byte or a []rune, Go does O(n) work even though conversions are "syntax".

    There is no standard library function that will do this conversion for you. You could make one with reflect, but it would be slower than the three line option.

    Example with reflection:

    func InterfaceSlice(slice interface{}) []interface{} {
        s := reflect.ValueOf(slice)
        if s.Kind() != reflect.Slice {
            panic("InterfaceSlice() given a non-slice type")
        }
    
        // Keep the distinction between nil and empty slice input
        if s.IsNil() {
            return nil
        }
    
        ret := make([]interface{}, s.Len())
    
        for i:=0; i

    Your best option though is just to use the lines of code you gave in your question:

    b := make([]interface{}, len(a))
    for i := range a {
        b[i] = a[i]
    }
    

提交回复
热议问题