samedi 4 février 2023

What is best pattern to reuse Go interface without tripping cyclic dependencies

I have this simple package declaration where package "a" defines an interface "A" but I need to use the interface in package "b" for type inference and then the implementation of b.Request() in DoRequest() of "a" this means having to import the package in a cyclic way.

My question is if there is a none complicated approach to this design to avoid compiler cyclic dependency error ?.

NOTE to avoid putting "a" and "b" in the same package

package b

import "a"

func Request(t a.A){
m := t.GetMethod()
payload := t.GetPayload()
}

And Package "a" declaration

package a

import "b"


type A interface {
 GetMethod () string
 GetPayload () string
}

type ImplimentA struct {
}

func (imp ImplimentA)GetMethod() string{
return ""
}

func (imp  ImplimentA) GetPayload() string{
return ""
}

func (imp ImplimentA) DoRequest(){
  b.Request(imp)
}

Aucun commentaire:

Enregistrer un commentaire