1 year ago
#387066
Shreyas G
golang struct composition using interface
I have a regester which can be registered using different services, i want to access the child method - search based on the service passed. Since the methods are common i want to use a single regester and dynamically access the method based on the service. I have used struct composition and made service as parent which is in both other services. Problem is i am passing the service as interface in newProductService and newOrderService as an APIInterface and parent service struct makes the call to search in regester. But by default parent service based Search is called, i want it to call the actual service based Search.
package main
import "fmt"
type APIService interface {
Search() string
Regester(prefix string)
}
type service struct {
}
func (p *service) Regester(prefix string) {
fmt.Println(prefix, "register")
s := p.Search()
fmt.Println(s)
}
func (p *service) Search() string {
return "parent search"
}
type OrderService struct {
service
}
type ProductService struct {
service
}
func NewProductService() APIService {
fmt.Println("reached prod service")
return &ProductService{}
}
func NewOrderService() APIService {
fmt.Println("reached order service")
return &OrderService{}
}
func (p *ProductService) Search() string {
return "prod serach"
}
func (p *OrderService) Search() string {
return "order search"
}
func main() {
pr := NewProductService()
po := NewOrderService()
pr.Regester("products")
po.Regester("orders")
}
go
struct
interface
composition
manticore
0 Answers
Your Answer