为什么详细介绍的GO语言程序中的接口字段访问起作用?

huangapple go评论73阅读模式
英文:

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

问题

我已经定义了2个接口{Main,Sub}和一个名为HumanStruct的结构体在以下链接的代码中。我知道为什么s1.(Main).Title()可以工作。但我想知道为什么m.(Sub).Name()可以工作。这里的'm'是Main类型的变量。这个Main接口没有'Sub'字段。那么它是如何工作的?

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())
}
英文:

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())
}

答案1

得分: 3

类型断言表达式m.(Sub)的结果是类型Sub。接口Sub有一个可以调用的Name()方法。

m断言为Sub的类型成功,因为m中的值是HumanStruct类型,而该类型满足Sub接口。

英文:

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.

huangapple
  • 本文由 发表于 2015年12月13日 13:31:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/34248302.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定