From a4244372c8f9d79b5935c75b2d5b74bf3a7f6a50 Mon Sep 17 00:00:00 2001 From: ireina7 Date: Mon, 22 May 2023 04:38:05 +0800 Subject: [PATCH] Fixed recursive rule bug --- summoner.go | 32 +++++++++++++++++++++----------- summoner_test.go | 15 +++++++++++++++ 2 files changed, 36 insertions(+), 11 deletions(-) diff --git a/summoner.go b/summoner.go index 205ff38..79c2167 100644 --- a/summoner.go +++ b/summoner.go @@ -1,7 +1,6 @@ package summoner import ( - "fmt" "reflect" ) @@ -39,8 +38,9 @@ func Transfrom[A, B any](s *Summoner[A]) *Summoner[B] { } } -func (self *Summoner[A]) tryBuild() (A, error) { - t := TypeOf[A]() +func (self *Summoner[A]) tryBuild(t reflect.Type) (any, error) { + // t := TypeOf[A]() + // fmt.Println("Try build", t) r := reflect.New(t) i := 0 var a A @@ -54,30 +54,40 @@ func (self *Summoner[A]) tryBuild() (A, error) { field.Set(dependency) i += 1 } - ans, ok := r.Interface().(*A) - if !ok { - return a, fmt.Errorf("Type conversion error: %v", r) - } - return *ans, nil + ans := r.Elem().Interface() + return ans, nil } func (self *Summoner[A]) Summon() (A, error) { t := TypeOf[A]() + // fmt.Println("Summon", t) ev, ok := self.instances[t] if ok { return ev.(A), nil } - // var a A + var a A // return a, fmt.Errorf("Instance of %v not found", t) - return self.tryBuild() + x, err := self.tryBuild(t) + if err != nil { + return a, err + } + return x.(A), nil + } func (self *Summoner[A]) SummonType(t reflect.Type) (any, error) { + // fmt.Println("Summon", t) ev, ok := self.instances[t] if ok { return ev, nil } - return nil, fmt.Errorf("Instance of %v not found", t) + // return nil, fmt.Errorf("Instance of %v not found", t) + var a A + x, err := self.tryBuild(t) + if err != nil { + return a, err + } + return x, nil } func (self *Summoner[A]) Given(ev A) error { diff --git a/summoner_test.go b/summoner_test.go index d078bed..116bb5c 100644 --- a/summoner_test.go +++ b/summoner_test.go @@ -27,6 +27,12 @@ func TestSummoner(t *testing.T) { panic(err) } t.Log(es.Debug(Person{0, "Tom", 10})) + + ed, err := Summon[Recursive[Person]]() + if err != nil { + panic(err) + } + ed.Log(Person{1, "Jack", 14}) } type Person struct { @@ -58,3 +64,12 @@ type Debug[A any] struct { func (self *Debug[A]) Debug(a A) string { return fmt.Sprintf("Debug: %s", self.Show.Show(a)) } + +type Recursive[A any] struct { + Debugger Debug[A] +} + +func (self *Recursive[A]) Log(a A) { + fmt.Println(self.Debugger.Debug(a)) + fmt.Println(self.Debugger.Show.Show(a)) +}