Below is simplified Go code.
As you can see, it wrote twice String(), is there any way to write just once?
type A struct {
Name string
}
func (u A) String() string {
out, err := json.MarshalIndent(u, "", "\t")
return fmt.Sprintf("A:\n" + string(out))
}
type B struct {
Name string
}
func (u B) String() string {
out, err := json.MarshalIndent(u, "", "\t")
return fmt.Sprintf("B:\n" + string(out))
}
Something like to implement a struct Base, which has a method did(),
then struct A and struct B implement struct Base, so they can call did() without need to implement did() itself again.
==============
Edited:
The previous sample code is not very clear, now I changed it.
The struct A and struct B have different fields, and how can we write String() just once, then apply to two structs?
type A struct {
Name string
Status string
}
func (u A) String() string {
out, err := json.MarshalIndent(u, "", "\t")
return fmt.Sprintf("A:\n" + string(out))
}
type B struct {
ID int
Logo string
}
func (u B) String() string {
out, err := json.MarshalIndent(u, "", "\t")
return fmt.Sprintf("B:\n" + string(out))
}