How do I translate the following Java code to 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);
}
}
Type NamePrinter
can reference an instance of both NamePrinterWithoutGreeting
and NamePrinterWithGreeting
:
void main(String[] args) {
a NamePrinter = new NamePrinterWithoutGreeting("Joe");
b NamePrinter = new NamePrinterWithGreeting("Joe");
a.print(); // prints "Joe"
b.print(); // prints "Hello, Joe"
}
Back to go
... I'd like to have an interface
of type NamePrinter
that could reference many different implementations... but I don't know how to do it. Here below is an implementation... but it is fine for just one case:
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())
}
Thank you.