walker

package module
v0.0.0-...-9f5ead8 Latest Latest
Warning

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

Go to latest
Published: Jan 17, 2022 License: MIT Imports: 3 Imported by: 0

README

Golang Struct Walker

A simple Go library for traversing nested structs. It largely relies on reflect methods, so be careful about performance.

Installing

go get -u github.com/armezit/struct-walker

Usage

package main

import (
	"fmt"
	walker "github.com/armezit/struct-walker"
	"reflect"
	"strings"
)

func main() {
	type Bar struct {
		AA string
		BB int
	}

	type Foo struct {
		A string
		B struct {
			B1 float64
			B2 float64
		}
		C struct {
			C1 uint
			C2 uint
		}
		D map[string]Bar
		E []Bar
	}

	// foo initialization
	foo := Foo{
		// ...
	}

	visitor := func(value reflect.Value, branch []interface{}, path []string, field *reflect.StructField) {
		k := strings.Join(path, ".")
		v := value.Interface()
		fmt.Printf("%s: %v", k, v)
	}
	walker.Walk(foo, visitor)
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Walk

func Walk(s interface{}, visitor Visitor)

Walk walks the given struct interface recursively and calls the visitor at every node

Types

type Visitor

type Visitor func(value reflect.Value, branch []interface{}, path []string, field *reflect.StructField)

Visitor is a function that will be called on each visited node. value is a non-map value, corresponding to the above path. branch is a slice containing consecutive interfaces used to arrive at the given value. path is a slice containing consecutive keys used to arrive at the given value.

Jump to

Keyboard shortcuts

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