reflection

package
v0.4.2 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2022 License: MIT Imports: 4 Imported by: 0

Documentation

Overview

Package reflection extends reflect package with functions commonly used while using reflection functionality making it easier to call reflect method, set values, parse/convert values or use generic TypeOf.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	ErrNotAddresable = errors.New("field is not addressable")
)
View Source
var (
	ErrNotSupportedType = errors.New("target type is not supported by parser")
)

Functions

func GetFieldValueFor

func GetFieldValueFor(fieldType reflect.Type, rawValue any) (reflect.Value, error)

GetFieldValueFor returns a reflect.Value which matches fieldType and value of rawValue. If rawValue type is different than fieldType then it's converter or parsed to match the type.

func InParamTypes

func InParamTypes(fn reflect.Type) []reflect.Type

InParamTypes returns a function input parameter types. It returns nil if the 'fn' Kind is not Func.

func OutParamTypes

func OutParamTypes(fn reflect.Type) []reflect.Type

OutParamTypesOf returns a function output parameter types. It returns nil if the 'fn' Kind is not Func.

func Parse

func Parse(s string, target interface{}) (interface{}, error)

Parse returns the parsed value with target type. s can be parsed to any of these types: string, int, float, complex, bool, time.Duration, time.Time, error. It accepts both pointer or non-pointer type. If s value is convertible to target it will return the converted value. Returns ErrNotSupportedType error if cannot parse to target value.

Example
package main

import (
	"fmt"

	"github.com/Prastiwar/Go-flow/reflection"
)

func main() {
	parsed, err := reflection.Parse("1", int8(0))
	if err != nil {
		panic(err)
	}

	asInt, ok := parsed.(int8)
	fmt.Println(asInt, ok)

}
Output:
1 true

func SetFieldValue

func SetFieldValue(field reflect.Value, rawValue any) error

SetFieldValue calls GetFieldValueFor and sets got value directly to field or error if occurred. If rawValue is nil - it will not set nil value to field - use reflect.ValueOf(nil) in this case.

func TogglePointer

func TogglePointer(u reflect.Type) reflect.Type

TogglePointer if u kind is pointer, returns its element else returns u as pointer.

func TypeOf

func TypeOf[T any]() reflect.Type
Example
package main

import (
	"fmt"

	"github.com/Prastiwar/Go-flow/reflection"
)

func main() {
	strTyp := reflection.TypeOf[fmt.Stringer]()

	fmt.Println(strTyp)

}
Output:
fmt.Stringer

Types

This section is empty.

Directories

Path Synopsis
Package cast provides helpful functions for casting.
Package cast provides helpful functions for casting.

Jump to

Keyboard shortcuts

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