I found its weird, why []string can not be converted to []interface{} ?
I think it should be possible, because:
but in the example below, it will be a compilation error
func f(args ...interface{}){
}
s := []string{"ssd", "rtt"}
f(s...)
why the language can't finish the conversion automatically?
Because []string
and []interface{}
have different in-memory layouts. This is obvious when you realise that an interface{}
variable needs to know the type of the value it contains.
For a []string
slice, the backing array only needs to hold the individual strings. For the []interface{}
slice, you've got both type information and the string values (well, pointers to the string values, since a string is larger than a single word of memory). So converting from one type to the other will involve copying the data.
It would be confusing for Go to automatically perform a conversion, since it would make it difficult to reason about code. For example, a function call f(s)
could modify the strings in the slice s
if it was declared to take a []string
argument, but not if it was declared to take a []interface{}
argument.
Slice is basically just a reference to the underlying array, start pointer, length and capacity. So if it would be possible, then consider the following:
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's array of interface{} now - we can do anything
// let's 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!
This issue exists in Java and C#. In practice it happens rarely, but still. Given that in Go there is no automatic type conversions like int32 -> int64 it makes sense that you are forced to create a []interface{} copy if you really want to send []string as []interface{}. This way there can be no surprise - you wrote it explicitly, you know what you're doing. And if function will modify []interface{} - it won't hurt original []string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With