dongling5411 2015-12-16 00:22
浏览 33
已采纳

GoLang:创建一个接受接口的函数(我来自PHP)

In PHP I can create an interface

interface Hello {
    public function bar();
}

And some classes that implements it

final class Foo implements Hello {
    public function bar() {
        // do something
    }
}

final class Bar implements Hello {
    public function bar() {
        // do something
    }
}

Then, I can also create a NewClass::bar() method that accept the interface.

final class NewClass {
    public function bar(Hello $hello) {
        // do something
    }
}

How can I do the same, in Golang?

type humanPlayer struct {
    name string
}

type botPlayer struct {
    name string
}

How can I realize same pattern in golang?

  • 写回答

1条回答 默认 最新

  • duanjianlu0506 2015-12-16 00:34
    关注
    package main
    
    import (
        "fmt"
    )
    
    type Namer interface {
        Name() string
    }
    
    type humanPlayer struct {
        name string
    }
    
    func (h *humanPlayer) Name() string {
        return h.name
    }
    
    type botPlayer struct {
        name string
    }
    
    func (b *botPlayer) Name() string {
        return b.name
    }
    
    func sayName(n Namer) {
        fmt.Printf("Hello %s
    ", n.Name())
    }
    
    func main() {
        human := &humanPlayer{
            name: "bob",
        }
        bot := &botPlayer{
            name: "tom",
        }
        sayName(human)
        sayName(bot)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 QTableWidget重绘程序崩溃
  • ¥15 51寻迹小车定点寻迹
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题
  • ¥15 Utunbu中vscode下cern root工作台中写的程序root的头文件无法包含
  • ¥15 麒麟V10桌面版SP1如何配置bonding