如何将以下Java代码转换为Go?

interface NamePrinter {
    void print();
}

class NamePrinterWithoutGreeting implements NamePrinter {
    private string name;

    public NamePrinterWithoutGreeting(string name) {
        this.name = name;
    }

    public void print() {
        System.out.println(this.name);
    }
}

class NamePrinterWithGreeting implements NamePrinter {
    private string name;

    public NamePrinterWithoutGreeting(string name) {
        this.name = name;
    }

    public void print() {
        System.out.println("Hello, " + this.name);
    }
}

类型NamePrinter可以引用NamePrinterWithoutGreetingNamePrinterWithGreeting的实例:
void main(String[] args) {
    a NamePrinter = new NamePrinterWithoutGreeting("Joe");
    b NamePrinter = new NamePrinterWithGreeting("Joe");

    a.print(); // prints "Joe"
    b.print(); // prints "Hello, Joe"
}

返回go ...我想要一个interface类型的NamePrinter,它可以引用许多不同的实现方式...但是我不知道该怎么做。下面是一个实现...但是仅在一种情况下可以:
type Person struct {
    name string
}

type NamePrinter interface {
    Create(name string)
    Print()
}

func Create(name string) *Person {
    n := Person{name}
    return &n
}

func (p *Person) print() {
    fmt.Println(p.name)
}

func main() {
    p := Create("joe")
    fmt.Println(p.Print())
}

谢谢。

最佳答案

您定义的任何类型,以及在其上实现与接口定义的方法签名相同的方法集的那个类型,都可以在需要该接口的位置使用该类型。

type NamePrinter interface {
    print()
}

type NamePrinterWithoutGreeting struct {
    name string
}

func (p *NamePrinterWithoutGreeting) print() {
    fmt.Println(p.name)
}

type NamePrinterWithGreeting struct {
    name string
}

func (p *NamePrinterWithGreeting) print() {
    fmt.Println("Hello, ", p.name)
}

type MyInt int

func (i MyInt) print() {
    fmt.Printf("Hello, %d\n", i)
}

type MyFunc func() string

func (f MyFunc) print() {
    fmt.Println("Hello,", f())
}
func main() {
    var a NamePrinter = &NamePrinterWithoutGreeting{"joe"}
    var b NamePrinter = &NamePrinterWithGreeting{"joe"}
    var i NamePrinter = MyInt(2345)
    var f NamePrinter = MyFunc(func() string { return "funk" })
    a.print()
    b.print()
    i.print()
    f.print()
}

https://play.golang.org/p/hW1q8eMve3

关于go - 一个接口(interface),多种实现,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45944052/

10-11 22:10
查看更多