V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
inhzus
V2EX  ›  Go 编程语言

怎样更好地实现多态?

  •  
  •   inhzus · 2019-08-06 19:58:37 +08:00 · 3005 次点击
    这是一个创建于 1732 天前的主题,其中的信息可能已经有所发展或是发生改变。

    问题:虽然这样间接地实现了多态,但是由于 Model 真的没有任何 method (方法)只有数据成员,这个类型定义为 interface{} 总之有些不优雅的感觉,想问下大家有没有更好的实现方法?

    代码见 gist (或下方的图片): https://gist.github.com/inhzus/b301db257c520c15466fc833aaaec7f6

    code

    第 1 条附言  ·  2019-08-06 20:48:48 +08:00
    暂时决定把使用时候的 type assertion 做的更确切一些就可以避免问题了。

    如果大家有更好的方法,请不吝赐教
    9 条回复    2019-08-06 21:20:32 +08:00
    way2create
        1
    way2create  
       2019-08-06 20:09:15 +08:00
    怎么我这 gist 都打不开...github 又可以
    inhzus
        2
    inhzus  
    OP
       2019-08-06 20:12:13 +08:00
    @way2create #1 gist 貌似不架梯子确实比较难出去... 看图片好了= =
    mm163
        3
    mm163  
       2019-08-06 20:52:02 +08:00
    if 来 if 去的,还什么多态?
    inhzus
        4
    inhzus  
    OP
       2019-08-06 20:57:33 +08:00
    @mm163 #3 用 switch 就行了,示例代码而已,没必要纠结这个吧
    mm163
        5
    mm163  
       2019-08-06 21:02:00 +08:00
    接口的多种不同的实现方式即为多态,只要针对不同的类型实现同一个接口就行了,基本的用法。
    import "fmt"

    type Model interface{
    PrintValues()
    }

    type A struct {
    x int
    }

    type B struct {
    A
    y int
    }

    func (a*A) PrintValues(){
    fmt.Printf("x: %v", a.x)
    }
    func (b*B) PrintValues(){
    fmt.Printf("x: %v, y: %v", b.x, b.y)
    }
    func test(model Model) {
    model. PrintValues()
    }
    cabing
        6
    cabing  
       2019-08-06 21:07:04 +08:00
    针对接口编程。

    不要随便使用 iterface{}这种类型转来转去的。这和随意转成 void*有啥区别。
    jessun1990
        7
    jessun1990  
       2019-08-06 21:17:42 +08:00 via Android
    @mm163 同意,用接口实现多态最合适。
    reus
        8
    reus  
       2019-08-06 21:20:09 +08:00
    我不反对使用 interface{},尤其是需要动态性时,用 interface{} 是必然的

    不过你这个代码,和多态实在没什么关系。多态是不涉及 type assertion 的
    reus
        9
    reus  
       2019-08-06 21:20:32 +08:00
    @cabing void* 无类型,接口有类型,这就是最大的区别
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   938 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 23:23 · PVG 07:23 · LAX 16:23 · JFK 19:23
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.