Problem:
You have a central package that provides interfaces and depends on other packages that offer implementations of those interfaces. However, including these dependent packages in the central package creates a cyclic dependency, which Go does not allow.
Standard Library Solutions:
Custom Registry Solution:
Choosing the Best Solution:
The ideal approach depends on specific requirements:
Code Example for Custom Registry Solution:
// Package pi defines an interface I. package pi type I interface { // Some method. DoSomething() } // Package pa implements I with type A. package pa import "pi" type A struct{} func (a *A) DoSomething() { // Some implementation. } // Package pb implements I with type B. package pb import "pi" type B struct{} func (b *B) DoSomething() { // Some implementation. } // Package pf provides a factory to create instances of I. package pf import ( "pi" "pa" "pb" ) // NewClient returns an instance of I based on a flag. func NewClient(flag string) pi.I { switch flag { case "a": return &pa.A{} case "b": return &pb.B{} default: panic("Invalid flag") } }
The above is the detailed content of How to Register Go Packages Without Creating Cyclic Dependencies?. For more information, please follow other related articles on the PHP Chinese website!