dongzhoulong1797 2018-06-01 09:05
浏览 76

Go接口值是实现该接口的整个变量吗?

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?

  • 写回答

2条回答 默认 最新

  • doulupian8725 2018-06-01 09:14
    关注

    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?

    评论

报告相同问题?