Why the [] string cannot be converted to the [] interface {} in golang

I found it strange why the [] string cannot be converted to the [] interface {}?

I think this should be possible because:

  • all these fragments
  • each element of the string [] is a string, which of course is the {} interface

but in the example below it will be a compilation error

func f(args ...interface{}){

}
s := []string{"ssd", "rtt"}
f(s...)

why can't the language complete the conversion automatically?

+4
source share
2 answers

Because []stringand []interface{}have different layouts in memory. This is obvious when you understand that a variable interface{}must know the type of value contained in it.

[]string, . []interface{} (, , ). .

, Go , . , f(s) s, , []string, []interface{}.

+5

Slice - , , . , , :

sliceOfStrings := []string{"one", "two", "three"}
// prints ONE TWO THREE
for i := range sliceOfStrings {
    fmt.Println(strings.ToUpper(sliceOfStrings[i]))
}

// imagine this is possible
var sliceOfInterface = []interface{}(sliceOfStrings)
// since it array of interface{} now - we can do anything
// let put integer into the first position
sliceOfInterface[0] = 1
// sliceOfStrings still points to the same array, and now "one" is replaced by 1
fmt.Println(strings.ToUpper(sliceOfStrings[0])) // BANG!

Java #. , . , Go , int32 → int64, , [] {}, [] [] interface {}. , , , , . [] {} - [] .

+5

Source: https://habr.com/ru/post/1523466/


All Articles