Jsmith
Jsmith

Reputation: 615

Why the interface field access in the GO language program given in details works?

I have defined 2 interfaces {Main, Sub} and a structure HumanStruct in the code in the following link. I know why s1.(Main).Title() works.But I want to know why m.(Sub).Name() works. Here 'm' is variable of interface Main type. This Main interface has no field 'Sub'. Then how it works?

package main

import "fmt"

type Main interface {
    Title() string
}

type Sub interface {
    Main
    Name() string
}

type HumanStruct struct {
    name  string
    title string
}

func (hs HumanStruct) Name() string {
    return hs.name
}

func (hs HumanStruct) Title() string {
    return hs.title
}

func main() {
    h := HumanStruct{name: "John", title: "Kings"}

    var m Main
    m = h

    var s1 Sub
    s1 = h

    fmt.Println("From main: ", m.(Sub).Name())
    fmt.Println("From sub:  ", s1.(Main).Title())
}

Upvotes: 0

Views: 53

Answers (1)

Thundercat
Thundercat

Reputation: 121049

The result of the type assertion expression m.(Sub) is of type Sub. Interface Sub has a Name() method which you can call.

The type assertion of m to Sub succeeds because the value in m is a HumanStruct and that type satisfies the Sub interface.

Upvotes: 3

Related Questions