Skip to content

gontainer/reflectpro

Repository files navigation

Go Reference Tests Coverage Status Go Report Card Quality Gate Status

Reflectpro

Simple, elegant, and intuitive callers, copiers, getters and setters.

Examples

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.

type Person struct {
	name string
	age  int
}

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

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

Copier

var (
    from = []any{int(1), uint(2), float32(3), float64(4)}
    to   []uint64
)
_ = copier.Copy(from, &to, true) // convert
fmt.Printf("%#v\n", to)
// Output: []uint64{0x1, 0x2, 0x3, 0x4}

Getter

In the following example, we read an unexported field of the given struct.

person := struct {
    name string
}{
    name: "Mary",
}
v, _ := getter.Get(person, "name")
fmt.Println(v)
// Output: Mary

Setter

In the following example, we have a pointer to any that stores a struct, instead of having a direct pointer to a struct. Since it is an unaddressable value, the reflect package from the standard library does not allow assigning a new value to this field. Setter handles that by creating an addressable copy.

var person any
person = struct {
    name string
}{}
_ = setter.Set(&person, "name", "Mary", false)
fmt.Println(person)
// Output: {Mary}