douyiyang6317 2014-09-08 17:44
浏览 43
已采纳

接口并将匿名字段嵌入到结构中

I'm trying to represent a human wearing glasses near a window when a nearby explosion occurs. main is a sketch of what should be done during the explosion. Something should gather up a list of objects in proximity of the explosion and do specific things (such as shattering or melting) for each of them. The glass and window shatter as expected, but for some reason the human also shatters. Why?

package main
import "fmt"
type Human struct { Glasses }
type Glasses struct {}
type Shatterable interface { shatter() }
func (g Glasses) shatter() {}
type Window struct {}
func (w Window) shatter() {}

func main() {
    h := Human{Glasses{}}
    objectsInProximity := []interface{}{h,h.Glasses,Window{}}
    for _,o := range objectsInProximity {
        shatter(o)
    }
}

func shatter(i interface{}) {
    s, ok := i.(Shatterable)
    if ok {
        fmt.Printf("shattering a %T
", s)
        s.shatter()
    }
}
$ go run a.go
shattering a main.Human
shattering a main.Glasses
shattering a main.Window
  • 写回答

1条回答 默认 最新

  • dqfxao2898 2014-09-08 17:52
    关注

    As mentioned in this thread:

    We're talking about anonymous fields of a struct (http://golang.org/ref/spec#Struct_types).

    (modified version, as the term superset is confusing)

    A struct with an anonymous field satisfies every interface with all the interface methods declared by the anonymous field or the struct itself.

    type Human struct { Glasses }
    

    Since Glasses can be shattered, Human also satisfy the same interface.


    Note: embedding anonymous field in a struct is the closest to "inheritance", even though the answer to "Golang: what's the point of interfaces when you have multiple inheritance" reminds us that:

    Go doesn't have inheritance.
    If Man 'extended' Human (by having it as an anonymous field), any method that used Human as an argument, would not be able to take Man as an argument.

    (That means here Human extends... Glasses?! That might show some kind of design imperfection)

    I explained before in "If struct A is embedded in B, can methods on A access method and fields of B?" that this isn't true sub-typing.

    Interfaces enable functions to have a 'placeholder' parameter which can take different structs as an argument.

    Here, if Human isn't supposed to be shattered, it shouldn't include the anonymous field Glasses.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了