The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
inhzus

怎样更好地实现多态?

  •  
  •   inhzus · Aug 6, 2019 · 3531 views
    This topic created in 2485 days ago, the information mentioned may be changed or developed.

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

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

    code

    Supplement 1  ·  Aug 6, 2019
    暂时决定把使用时候的 type assertion 做的更确切一些就可以避免问题了。

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

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

    不过你这个代码,和多态实在没什么关系。多态是不涉及 type assertion 的
    reus
        9
    reus  
       Aug 6, 2019
    @cabing void* 无类型,接口有类型,这就是最大的区别
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3077 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 62ms · UTC 14:38 · PVG 22:38 · LAX 07:38 · JFK 10:38
    ♥ Do have faith in what you're doing.