Home > database >  How []interface{} in Go is implemented?
How []interface{} in Go is implemented?

Time:12-11

In Go I can do something like this:

func main() {
    var intSlice []interface{}
    intSlice = append(intSlice, "hello world")
    intSlice = append(intSlice, 1)
    for _, v := range intSlice {
        fmt.Println(v)   // hello world
                         // 1
    }
}

Since a slice is deep down an array, without given a specific type to that array, how can Go know the layout of this array's memory structure? If it's a []string then I know that for every iteration I have to add current address with 4 to get the next item's address, but for an interface{} how can Go knows what to do? I am confused. One possible explain for this is that interface{} is actually a pointer, so []interface{} stores pointers only, the value 1 or "hello world" is stored somewhere outside of the slice. Am I right about this?

CodePudding user response:

An interface is two values: a pointer to the value, and a pointer to the type of the value. So a []interface{} containing all int values is simply an array of interfaces, where each element containing those two values, with each element of the array pointing to the int value, and to its type.

  • Related