Trying to create a Clone() function with returns the “final” concrete type and using a reference to polymorphically create a clone of the final type, but hitting compile errors. Ideas/solution appreciated.
Is it possible to make the code below compile or is there an idiomatic way to achieve the polymorphic cloning with embedding of interface/struct ?
package main
import "fmt"
type Cloner[T any] interface {
Clone() T
}
type AI[T any] interface {
// Want all implementations to have a Clone() method that returns the final type
Cloner[AI[T]]
}
// implements the AI interface, by embedding the interface
type AS struct {
AI[int]
a int
}
func (as AS) Clone() AS {
return AS{a: as.a}
}
// implements the AI interface, by embedding the interface
type BS struct {
AI[int]
b string
}
func (bs BS) Clone() BS {
return BS{b: bs.b}
}
// implements the AI interface by embedding AS struct
type CS struct {
AS
c int
}
func (cs CS) Clone() CS {
return CS{
AS: cs.Clone(), // error: cannot use cs.Clone() (value of type CS) as type AS in struct literal
c: cs.c,
}
}
func main() {
var aiRef AI[int]
// try to get a clone of concrete objects
aiRef = &AS{a: 10}
fmt.Printf("AS: %#v\n", aiRef.Clone())
// Compile error:
// ./main.go:42:10: cannot use &AS{…} (value of type *AS) as type AI[int] in assignment:
// *AS does not implement AI[int] (wrong type for Clone method)
// have Clone() AS
// want Clone() AI[int]
aiRef = &BS{b: "hello"}
fmt.Printf("BS: %#v\n", aiRef.Clone())
// same compile error as above
aiRef = &CS{c: 10}
fmt.Printf("CS: %#v\n", aiRef.Clone())
// same compile error as above
}