Skip to content

Commit

Permalink
Fixed recursive rule bug
Browse files Browse the repository at this point in the history
  • Loading branch information
ireina7 committed May 21, 2023
1 parent f3c2623 commit a424437
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 11 deletions.
32 changes: 21 additions & 11 deletions summoner.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package summoner

import (
"fmt"
"reflect"
)

Expand Down Expand Up @@ -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
Expand All @@ -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 {
Expand Down
15 changes: 15 additions & 0 deletions summoner_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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))
}

0 comments on commit a424437

Please sign in to comment.