reflectpro

module
v1.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 21, 2024 License: MIT

README

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}

Directories

Path Synopsis
Package caller provides functions that allow calling other functions with unknown arguments.
Package caller provides functions that allow calling other functions with unknown arguments.
Package copier allows for copying a value to a variable with an unknown type.
Package copier allows for copying a value to a variable with an unknown type.
Package getter allows for read operations on fields of any struct.
Package getter allows for read operations on fields of any struct.
internal
Package setter allows for write operations on fields of any struct.
Package setter allows for write operations on fields of any struct.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL