Skip to content

Commit

Permalink
docs: caller
Browse files Browse the repository at this point in the history
  • Loading branch information
bkrukowski committed Mar 21, 2024
1 parent 936ff53 commit 02750f1
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 18 deletions.
14 changes: 10 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,20 +12,26 @@ Simple, elegant, and intuitive [callers](caller), [copiers](copier), [getters](g

## Caller

In the following example, we have a pointer to `any` that stores a `struct`,
instead of having a direct pointer to a `struct`.
The receiver is a pointer, so eventually we cannot call the given method.
**Caller** handles that by creating a pointer to a copy of that value.

```go
type Person struct {
name string
age int
}

func (p *Person) SetName(n string) {
p.name = n
}

func ExampleCallMethod() {
p := &Person{}
func Example() {
var p any = &Person{age: 25}
_, _ = caller.CallMethod(p, "SetName", []any{"Mary"}, false)
fmt.Println(p.name)
// Output: Mary
fmt.Printf("%+v\n", p)
// Output: &{name:Mary age:25}
}
```

Expand Down
36 changes: 22 additions & 14 deletions caller/examples_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,11 @@ import (

type Person struct {
name string
age int
}

func NewPerson(name string) *Person {
return &Person{name: name}
func NewPerson(name string, age int) *Person {
return &Person{name: name, age: age}
}

func (p *Person) SetName(n string) {
Expand All @@ -45,10 +46,10 @@ func (p Person) WithName(n string) Person {
}

func ExampleCall_ok() {
p := &Person{}
p := &Person{age: 22}
_, _ = caller.Call(p.SetName, []any{"Mary"}, false)
fmt.Println(p.name)
// Output: Mary
fmt.Printf("%+v\n", p)
// Output: &{name:Mary age:22}
}

func ExampleCall_returnValue() {
Expand Down Expand Up @@ -84,21 +85,28 @@ func ExampleCall_error2() {
}

func ExampleCallProvider() {
p, _, _ := caller.CallProvider(NewPerson, []any{"Mary"}, false)
fmt.Printf("%+v", p)
// Output: &{name:Mary}
p, _, _ := caller.CallProvider(NewPerson, []any{"Mary", 21}, false)
fmt.Printf("%+v\n", p)
// Output: &{name:Mary age:21}
}

func ExampleCallMethod() {
p := &Person{}
p := &Person{age: 23}
_, _ = caller.CallMethod(p, "SetName", []any{"Mary"}, false)
fmt.Println(p.name)
// Output: Mary
fmt.Printf("%+v\n", p)
// Output: &{name:Mary age:23}
}

func ExampleCallMethod_unaddressable() {
var p any = &Person{age: 25}
_, _ = caller.CallMethod(p, "SetName", []any{"Mary"}, false)
fmt.Printf("%+v\n", p)
// Output: &{name:Mary age:25}
}

func ExampleCallWither() {
p := Person{}
var p any = Person{age: 30}
p2, _ := caller.CallWither(p, "WithName", []any{"Mary"}, false)
fmt.Printf("%+v", p2)
// Output: {name:Mary}
fmt.Printf("%+v\n", p2)
// Output: {name:Mary age:30}
}

0 comments on commit 02750f1

Please sign in to comment.