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

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

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'字段。那么它是如何工作的?

  1. package main
  2. import "fmt"
  3. type Main interface {
  4. Title() string
  5. }
  6. type Sub interface {
  7. Main
  8. Name() string
  9. }
  10. type HumanStruct struct {
  11. name string
  12. title string
  13. }
  14. func (hs HumanStruct) Name() string {
  15. return hs.name
  16. }
  17. func (hs HumanStruct) Title() string {
  18. return hs.title
  19. }
  20. func main() {
  21. h := HumanStruct{name: "John", title: "Kings"}
  22. var m Main
  23. m = h
  24. var s1 Sub
  25. s1 = h
  26. fmt.Println("From main: ", m.(Sub).Name())
  27. fmt.Println("From sub: ", s1.(Main).Title())
  28. }
英文:

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?

  1. package main
  2. import "fmt"
  3. type Main interface {
  4. Title() string
  5. }
  6. type Sub interface {
  7. Main
  8. Name() string
  9. }
  10. type HumanStruct struct {
  11. name string
  12. title string
  13. }
  14. func (hs HumanStruct) Name() string {
  15. return hs.name
  16. }
  17. func (hs HumanStruct) Title() string {
  18. return hs.title
  19. }
  20. func main() {
  21. h := HumanStruct{name: "John", title: "Kings"}
  22. var m Main
  23. m = h
  24. var s1 Sub
  25. s1 = h
  26. fmt.Println("From main: ", m.(Sub).Name())
  27. fmt.Println("From sub: ", s1.(Main).Title())
  28. }

答案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:

确定