Reputation: 7938
The section of appending to slices on the specification, mentions the following example:
var t []interface{}
t = append(t, 42, 3.1415, "foo") // t == []interface{}{42, 3.1415, "foo"}
I'm confused here, why can we append values of int
, float
and string
to a slice
whose elements are of interface
type? And why is the result of the append
like that? I tried hard/long, but I don't get it.
Upvotes: 0
Views: 59
Reputation:
Because:
all types implement the empty interface
For details read over the ref spec for interfaces.
interface
is similar to Object
in java where all types/classes/etc are also an Object
.
You can see this effect by using reflect
:
package main
import (
"fmt"
"reflect"
)
func main() {
var t []interface{}
z := append(t, "asdf", 1, 2.0)
fmt.Println(z)
for i := range z {
fmt.Println(reflect.TypeOf(z[i]))
}
}
Output:
[asdf 1 2]
string
int
float64
Why is it like this? Well, think about serialization especially of JSON objects; the types can be string, int, object, etc. This allows for deserialization without specifying a fully mapped struct (maybe you don't care and want only some of the data, etc). Basically, it allows you to have a form of "weak typing" in Go; while still being able to have strong typing.
As mentioned below, reflect
identifies the type for you. When programming though, you may have to do it manually.
Upvotes: 5