visit

package module
v1.1.1 Latest Latest
Warning

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

Go to latest
Published: Dec 29, 2019 License: MIT Imports: 1 Imported by: 0

README

visit

Go Report Card

A Go library to recursively visit data structures using reflection.

import "github.com/keilerkonzept/visit"

Get it

go get -u "github.com/keilerkonzept/visit"

Use it

import (
    "github.com/keilerkonzept/visit"

    "fmt"
    "reflect"
)

type myStruct struct {
    String string
    Map    map[string]myStruct
    Ptr    *myStruct
}

func main() {
	obj := &myStruct{
		String: "hello",
		Map: map[string]myStruct{
			"world": myStruct{String: "!"},
		},
	}
	obj.Ptr = obj

	var strings []string
	visit.Values(obj, func(value visit.ValueWithParent) (visit.Action, error) {
		if value.Kind() == reflect.String {
			strings = append(strings, value.String())
		}
		return visit.Continue, nil
	})
	fmt.Println(strings)
	// Output:
	// [hello world !]
}

Documentation

Overview

Package visit is a library to visit Go data structures (using reflection)

Example
type myStruct struct {
	String string
	Map    map[string]myStruct
	Ptr    *myStruct
}
obj := &myStruct{
	String: "hello",
	Map: map[string]myStruct{
		"world": {String: "!"},
	},
}
obj.Ptr = obj

var strings []string
Values(obj, func(value ValueWithParent) (Action, error) {
	if value.Kind() == reflect.String {
		strings = append(strings, value.String())
	}
	return Continue, nil
})
fmt.Println(strings)
Output:

[hello world !]

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Assign added in v1.1.0

func Assign(value ValueWithParent, newValue reflect.Value) error

Assign tries to assign `newValue` to the given `value`, and otherwise returns an error.

func TryAssign added in v1.1.0

func TryAssign(value ValueWithParent, newValue reflect.Value) bool

TryAssign tries to assign `newValue` to the given `value`, and returns a boolean indicating success.

func Values added in v1.1.0

func Values(obj interface{}, f Func) error

Values visits a structure, with cycle detection

func ValuesUnsafe added in v1.1.0

func ValuesUnsafe(obj interface{}, f Func) error

ValuesUnsafe visits a structure *without* performing cycle detection

Types

type Action

type Action action

Action is the type of visitor actions

const (
	Skip     Action = "Skip"
	Stop     Action = "Stop"
	Continue Action = "Continue"
)

Visitor actions

type Func added in v1.1.0

type Func func(ValueWithParent) (Action, error)

Func is a visitor function

type ValueWithParent added in v1.1.0

type ValueWithParent struct {
	reflect.Value
	Parent *ValueWithParent
	Index  reflect.Value
}

ValueWithParent is a reflect.Value with its parent container (if any) and the corresponding index value.

Jump to

Keyboard shortcuts

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