Nathan
Nathan

Reputation: 1354

Is a Go interface value an entire variable that implements the interface?

New to Go here. I was taking a tour of Go and came across one word that I was confused what it was.

It's the 11th page of the Method section here. It says, "interface values can be thought of as a tuple of a value and a concrete type."

My understanding is that an interface value is a variable that implements that interface. E.g.:

type Animal interface {
    run()
}

type Cat struct { … }

func main() {
    kitty := Cat{ … }
}

func (c Cat) run() { … }

Is kitty an interface value?

Upvotes: 2

Views: 334

Answers (2)

Ravi R
Ravi R

Reputation: 1782

"interface values can be thought of as a tuple of a value and a concrete type." -> The interface in a way just cares if your type implements the methods it needs. It's data structure stores two things : 1. The type which implements it 2. A value (of the type in #1)

Here's a simple example just to give you an idea what it is like:

package main

import (
    "fmt"
    "reflect"
)

type Animal interface {
    run()
}

type Cat struct {
    a int
}

func main() {
    kitty := Cat{2}
    var anim Animal
    fmt.Println(kitty)
    kitty.run()
    anim = kitty //interface
    fmt.Println(anim)
    anim.run()
    t := reflect.TypeOf(anim)
    v := reflect.ValueOf(anim)
    fmt.Println(t.String())
    fmt.Println(v)

}

func (c Cat) run() {
    fmt.Println("Have fun")
}

Output :

{2}
Have fun
{2}
Have fun
main.Cat
{2}

https://play.golang.org/p/xeozR3VT-9J though you'd need to read up more and try a few examples on your own to understand this better.

Upvotes: 1

icza
icza

Reputation: 417662

In your case since you used short variable declaration to create kitty, the type is inferred from the right-hand side expression, and type of kitty will be the concrete type Cat.

But since the Cat concrete type (non-interface type) implements the Animal interface type, you may assign a value of Cat to a variable whose type is Animal, like in this example:

kitty := Cat{}
var kitty2 Animal = kitty

"Implements" by spec means:

An interface type specifies a method set called its interface. A variable of interface type can store a value of any type with a method set that is any superset of the interface. Such a type is said to implement the interface.

Interface values, schemantically, contain a (value; type) pair, being the value stored in them, and their concrete type.

For more details about interface internals, read blog post: The Go Blog: The Laws of Reflection
And Go Data Structures: Interfaces (by Russ Cox).

For an introduction why interfaces are needed or how / when to use them, see Why are interfaces needed in Golang?

Upvotes: 5

Related Questions