gpt4 book ai didi

php - 高语 : create a function that accept an interface (I came from PHP)

转载 作者:数据小太阳 更新时间:2023-10-29 03:41:25 26 4
gpt4 key购买 nike

在 PHP 中我可以创建一个接口(interface)

interface Hello {
public function bar();
}

以及一些实现它的类

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

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

然后,我还可以创建一个接受该接口(interface)的 NewClass::bar() 方法。

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

我如何在 Golang 中做同样的事情?

type humanPlayer struct {
name string
}

type botPlayer struct {
name string
}

如何在 golang 中实现相同的模式?

最佳答案

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", n.Name())
}

func main() {
human := &humanPlayer{
name: "bob",
}
bot := &botPlayer{
name: "tom",
}
sayName(human)
sayName(bot)
}

关于php - 高语 : create a function that accept an interface (I came from PHP),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34301929/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com