Search code examples
go

Is an Interface a Pointer?


Suppose I have the following type definitions:

type ICat interface {
  Meow() string
} 

type Cat struct {   
  Name string
}

func (c Cat) Meow() string { 
  return "Meow" 
}

When I perform this operation:

var a Cat
a.Name = "Tom"

A struct of type Cat is allocated in memory and one of its fields gets assigned.

But, if perform the following operation:

var b ICat

What is exactly being allocated in memory? is a Golang Interface just an struct that holds a pointer to another struct? a "Boxed pointer"?.


Solution

  • An interface holds two things: a pointer to the underlying data, and the type of that data. So, when you declare

    var b ICat
    

    b contains those two elements.

    When you do:

    b:=Cat{}
    

    b now contains a pointer to a copy of Cat{}, and the fact that the data is a struct Cat.

    When you do:

    b:=&Cat{}
    

    b now contains a copy of the pointer to Cat{}, and the fact that it is a *Cat.