Skip to content

Commit

Permalink
new API and doc update
Browse files Browse the repository at this point in the history
  • Loading branch information
ireina7 committed May 21, 2023
1 parent a424437 commit 8b94c2b
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 1 deletion.
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ go get -u github.com/ireina7/summoner
```

### Usage
Summoner has two basic functions: `Summon` and `Given`.
`Summon[T]()` summons a value of type `T`,
`Given[T](T)` injects a value of type `T`.
```go
import "fmt"
import summoner "github.com/ireina7/summoner"
Expand Down Expand Up @@ -174,5 +177,14 @@ func main() {
}
```

## API for golang compiler version before 1.18
Summoner also has API for non-generic style:
```go
func SummonType(t reflect.Type) (any, error)
func GivenType(instance any, t reflect.Type) error
```
Without generics, one need to pass `reflect.Type` value.


## Contribution
Any new ideas?
4 changes: 4 additions & 0 deletions summoner.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@ func Given[I any](instance I) error {
return Transfrom[any, I](&global).Given(instance)
}

func GivenType(instance any, t reflect.Type) error {
return global.GivenType(instance, t)
}

func Transfrom[A, B any](s *Summoner[A]) *Summoner[B] {
return &Summoner[B]{
instances: s.instances,
Expand Down
28 changes: 27 additions & 1 deletion summoner_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@ import (

func TestSummoner(t *testing.T) {

Given[Show[Person]](new(ShowPerson))
// Given[Show[Person]](new(ShowPerson))
GivenType(new(ShowPerson), TypeOf[Show[Person]]())
Given[Show[int]](new(ShowInt))
Given[Show[string]](new(ShowString))

ev, err := Summon[Show[Person]]()
if err != nil {
Expand All @@ -33,6 +35,13 @@ func TestSummoner(t *testing.T) {
panic(err)
}
ed.Log(Person{1, "Jack", 14})

ea, err := SummonType(TypeOf[App[Person]]())
if err != nil {
panic(err)
}
xx := ea.(App[Person])
xx.Execute(Person{1, "Jack", 14})
}

type Person struct {
Expand All @@ -57,6 +66,12 @@ func (ev *ShowInt) Show(i int) string {
return fmt.Sprintf("Integer: %v", i)
}

type ShowString struct{}

func (ev *ShowString) Show(s string) string {
return s
}

type Debug[A any] struct {
Show Show[A]
}
Expand All @@ -73,3 +88,14 @@ func (self *Recursive[A]) Log(a A) {
fmt.Println(self.Debugger.Debug(a))
fmt.Println(self.Debugger.Show.Show(a))
}

type App[A any] struct {
Show Show[string]
Recursive Recursive[A]
}

func (app *App[A]) Execute(a A) {
fmt.Println("---------------------")
fmt.Println(app.Show.Show("This is a test!"))
app.Recursive.Log(a)
}

0 comments on commit 8b94c2b

Please sign in to comment.