如何将以下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
可以引用NamePrinterWithoutGreeting
和NamePrinterWithGreeting
的实例:
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())
}
谢谢。
答案 0 :(得分:3)
您定义的任何类型,以及在其上实现一组与接口定义的签名相同的方法的类型,该类型可以在您期望该接口的位置使用。
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()
}