英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论