reflections

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2020 License: MIT Imports: 3 Imported by: 249

README

Reflections

Package reflections provides high level abstractions above the golang reflect library.

Reflect library is very low-level and can be quite complex when it comes to do simple things like accessing a structure field value, a field tag...

The purpose of reflections package is to make developers life easier when it comes to introspect structures at runtime. Its API is inspired from python language (getattr, setattr, hasattr...) and provides a simplified access to structure fields and tags.

Reflections is an open source library under the MIT license. Any hackers are welcome to supply ideas, features requests, patches, pull requests and so on: see Contribute

Documentation

Documentation is available at http://godoc.org/github.com/oleiade/reflections

Usage

Accessing structure fields
GetField

GetField returns the content of a structure field. It can be very usefull when you'd wanna iterate over a struct specific fields values for example. You can whether provide GetField a structure or a pointer to structure as first argument.

    s := MyStruct {
        FirstField: "first value",
        SecondField: 2,
        ThirdField: "third value",
    }

    fieldsToExtract := []string{"FirstField", "ThirdField"}

    for _, fieldName := range fieldsToExtract {
        value, err := reflections.GetField(s, fieldName)
        DoWhatEverWithThatValue(value)
    }
GetFieldKind

GetFieldKind returns the reflect.Kind of a structure field. It can be used to operate type assertion over a structure fields at runtime. You can whether provide GetFieldKind a structure or a pointer to structure as first argument.

    s := MyStruct{
        FirstField:  "first value",
        SecondField: 2,
        ThirdField:  "third value",
    }

    var firstFieldKind reflect.String
    var secondFieldKind reflect.Int
    var err error

    firstFieldKind, err = GetFieldKind(s, "FirstField")
    if err != nil {
        log.Fatal(err)
    }

    secondFieldKind, err = GetFieldKind(s, "SecondField")
    if err != nil {
        log.Fatal(err)
    }
GetFieldType

GetFieldType returns the string literal of a structure field type. It can be used to operate type assertion over a structure fields at runtime. You can whether provide GetFieldType a structure or a pointer to structure as first argument.

    s := MyStruct{
        FirstField:  "first value",
        SecondField: 2,
        ThirdField:  "third value",
    }

    var firstFieldKind string
    var secondFieldKind string
    var err error

    firstFieldKind, err = GetFieldType(s, "FirstField")
    if err != nil {
        log.Fatal(err)
    }

    secondFieldKind, err = GetFieldType(s, "SecondField")
    if err != nil {
        log.Fatal(err)
    }
GetFieldTag

GetFieldTag extracts a specific structure field tag. You can whether provide GetFieldTag a structure or a pointer to structure as first argument.

    s := MyStruct{}

    tag, err := reflections.GetFieldTag(s, "FirstField", "matched")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(tag)

    tag, err = reflections.GetFieldTag(s, "ThirdField", "unmatched")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(tag)
HasField

HasField asserts a field exists through structure. You can whether provide HasField a structure or a pointer to structure as first argument.

    s := MyStruct {
        FirstField: "first value",
        SecondField: 2,
        ThirdField: "third value",
    }

    // has == true
    has, _ := reflections.HasField(s, "FirstField")

    // has == false
    has, _ := reflections.HasField(s, "FourthField")
Fields

Fields returns the list of a structure field names, so you can access or modify them later on. You can whether provide Fields a structure or a pointer to structure as first argument.

    s := MyStruct {
        FirstField: "first value",
        SecondField: 2,
        ThirdField: "third value",
    }

    var fields []string

    // Fields will list every structure exportable fields.
    // Here, it's content would be equal to:
    // []string{"FirstField", "SecondField", "ThirdField"}
    fields, _ = reflections.Fields(s)
Items

Items returns the structure's field name to values map. You can whether provide Items a structure or a pointer to structure as first argument.

    s := MyStruct {
        FirstField: "first value",
        SecondField: 2,
        ThirdField: "third value",
    }

    var structItems map[string]interface{}

    // Items will return a field name to
    // field value map
    structItems, _ = reflections.Items(s)
Tags

Tags returns the structure's fields tag with the provided key. You can whether provide Tags a structure or a pointer to structure as first argument.

    s := MyStruct {
        FirstField: "first value",      `matched:"first tag"`
        SecondField: 2,                 `matched:"second tag"`
        ThirdField: "third value",      `unmatched:"third tag"`
    }

    var structTags map[string]string

    // Tags will return a field name to tag content
    // map. Nota that only field with the tag name
    // you've provided which will be matched.
    // Here structTags will contain:
    // {
    //     "FirstField": "first tag",
    //     "SecondField": "second tag",
    // }
    structTags, _ = reflections.Tags(s, "matched")
Set a structure field value

SetField update's a structure's field value with the one provided. Note that unexported fields cannot be set, and that field type and value type have to match.

    s := MyStruct {
        FirstField: "first value",
        SecondField: 2,
        ThirdField: "third value",
    }

    // In order to be able to set the structure's values,
    // a pointer to it has to be passed to it.
    _ := reflections.SetField(&s, "FirstField", "new value")

    // If you try to set a field's value using the wrong type,
    // an error will be returned
    err := reflection.SetField(&s, "FirstField", 123)  // err != nil

Important notes

  • unexported fields cannot be accessed or set using reflections library: the golang reflect library intentionaly prohibits unexported fields values access or modifications.

Contribute

  • Check for open issues or open a fresh issue to start a discussion around a feature idea or a bug.
  • Fork the repository_ on GitHub to start making your changes to the master branch (or branch off of it).
  • Write tests which shows that the bug was fixed or that the feature works as expected.
  • Send a pull request and bug the maintainer until it gets merged and published. :) Make sure to add yourself to AUTHORS_.

the repository AUTHORS

Bitdeli Badge

Documentation

Overview

Package reflections provides high level abstractions above the reflect library.

Reflect library is very low-level and as can be quite complex when it comes to do simple things like accessing a structure field value, a field tag...

The purpose of reflections package is to make developers life easier when it comes to introspect structures at runtime. It's API is freely inspired from python language (getattr, setattr, hasattr...) and provides a simplified access to structure fields and tags.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Fields

func Fields(obj interface{}) ([]string, error)

Fields returns the struct fields names list. obj can whether be a structure or pointer to structure.

Example
package main

import (
	"fmt"

	"github.com/oleiade/reflections"
)

type MyStruct struct {
	MyEmbeddedStruct
	FirstField  string `matched:"first tag"`
	SecondField int    `matched:"second tag"`
	ThirdField  string `unmatched:"third tag"`
}

type MyEmbeddedStruct struct {
	EmbeddedField string
}

func main() {
	s := MyStruct{
		FirstField:  "first value",
		SecondField: 2,
		ThirdField:  "third value",
	}

	var fields []string

	// Fields will list every structure exportable fields.
	// Here, it's content would be equal to:
	// []string{"FirstField", "SecondField", "ThirdField"}
	fields, _ = reflections.Fields(s)
	fmt.Println(fields)
}
Output:

func FieldsDeep

func FieldsDeep(obj interface{}) ([]string, error)

FieldsDeep returns "flattened" fields (fields from anonymous inner structs are treated as normal fields)

func GetField

func GetField(obj interface{}, name string) (interface{}, error)

GetField returns the value of the provided obj field. obj can whether be a structure or pointer to structure.

Example
package main

import (
	"fmt"
	"log"

	"github.com/oleiade/reflections"
)

type MyStruct struct {
	MyEmbeddedStruct
	FirstField  string `matched:"first tag"`
	SecondField int    `matched:"second tag"`
	ThirdField  string `unmatched:"third tag"`
}

type MyEmbeddedStruct struct {
	EmbeddedField string
}

func main() {
	s := MyStruct{
		FirstField:  "first value",
		SecondField: 2,
		ThirdField:  "third value",
	}

	fieldsToExtract := []string{"FirstField", "ThirdField"}

	for _, fieldName := range fieldsToExtract {
		value, err := reflections.GetField(s, fieldName)
		if err != nil {
			log.Fatal(err)
		}
		fmt.Println(value)
	}
}
Output:

func GetFieldKind

func GetFieldKind(obj interface{}, name string) (reflect.Kind, error)

GetFieldKind returns the kind of the provided obj field. obj can whether be a structure or pointer to structure.

Example
package main

import (
	"fmt"
	"log"
	"reflect"

	"github.com/oleiade/reflections"
)

type MyStruct struct {
	MyEmbeddedStruct
	FirstField  string `matched:"first tag"`
	SecondField int    `matched:"second tag"`
	ThirdField  string `unmatched:"third tag"`
}

type MyEmbeddedStruct struct {
	EmbeddedField string
}

func main() {
	s := MyStruct{
		FirstField:  "first value",
		SecondField: 2,
		ThirdField:  "third value",
	}

	var firstFieldKind reflect.Kind
	var secondFieldKind reflect.Kind
	var err error

	// GetFieldKind will return reflect.String
	firstFieldKind, err = reflections.GetFieldKind(s, "FirstField")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(firstFieldKind)

	// GetFieldKind will return reflect.Int
	secondFieldKind, err = reflections.GetFieldKind(s, "SecondField")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(secondFieldKind)
}
Output:

func GetFieldTag

func GetFieldTag(obj interface{}, fieldName, tagKey string) (string, error)

GetFieldTag returns the provided obj field tag value. obj can whether be a structure or pointer to structure.

Example
package main

import (
	"fmt"
	"log"

	"github.com/oleiade/reflections"
)

type MyStruct struct {
	MyEmbeddedStruct
	FirstField  string `matched:"first tag"`
	SecondField int    `matched:"second tag"`
	ThirdField  string `unmatched:"third tag"`
}

type MyEmbeddedStruct struct {
	EmbeddedField string
}

func main() {
	s := MyStruct{}

	tag, err := reflections.GetFieldTag(s, "FirstField", "matched")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(tag)

	tag, err = reflections.GetFieldTag(s, "ThirdField", "unmatched")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(tag)
}
Output:

func GetFieldType added in v1.0.1

func GetFieldType(obj interface{}, name string) (string, error)

GetFieldType returns the kind of the provided obj field. obj can whether be a structure or pointer to structure.

Example
package main

import (
	"fmt"
	"log"

	"github.com/oleiade/reflections"
)

type MyStruct struct {
	MyEmbeddedStruct
	FirstField  string `matched:"first tag"`
	SecondField int    `matched:"second tag"`
	ThirdField  string `unmatched:"third tag"`
}

type MyEmbeddedStruct struct {
	EmbeddedField string
}

func main() {
	s := MyStruct{
		FirstField:  "first value",
		SecondField: 2,
		ThirdField:  "third value",
	}

	var firstFieldType string
	var secondFieldType string
	var err error

	// GetFieldType will return reflect.String
	firstFieldType, err = reflections.GetFieldType(s, "FirstField")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(firstFieldType)

	// GetFieldType will return reflect.Int
	secondFieldType, err = reflections.GetFieldType(s, "SecondField")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(secondFieldType)
}
Output:

func HasField

func HasField(obj interface{}, name string) (bool, error)

HasField checks if the provided field name is part of a struct. obj can whether be a structure or pointer to structure.

Example
package main

import (
	"fmt"

	"github.com/oleiade/reflections"
)

type MyStruct struct {
	MyEmbeddedStruct
	FirstField  string `matched:"first tag"`
	SecondField int    `matched:"second tag"`
	ThirdField  string `unmatched:"third tag"`
}

type MyEmbeddedStruct struct {
	EmbeddedField string
}

func main() {
	s := MyStruct{
		FirstField:  "first value",
		SecondField: 2,
		ThirdField:  "third value",
	}

	// has == true
	has, _ := reflections.HasField(s, "FirstField")
	fmt.Println(has)

	// has == false
	has, _ = reflections.HasField(s, "FourthField")
	fmt.Println(has)
}
Output:

func Items

func Items(obj interface{}) (map[string]interface{}, error)

Items returns the field - value struct pairs as a map. obj can whether be a structure or pointer to structure.

Example
package main

import (
	"fmt"

	"github.com/oleiade/reflections"
)

type MyStruct struct {
	MyEmbeddedStruct
	FirstField  string `matched:"first tag"`
	SecondField int    `matched:"second tag"`
	ThirdField  string `unmatched:"third tag"`
}

type MyEmbeddedStruct struct {
	EmbeddedField string
}

func main() {
	s := MyStruct{
		FirstField:  "first value",
		SecondField: 2,
		ThirdField:  "third value",
	}

	var structItems map[string]interface{}

	// Items will return a field name to
	// field value map
	structItems, _ = reflections.Items(s)
	fmt.Println(structItems)
}
Output:

func ItemsDeep

func ItemsDeep(obj interface{}) (map[string]interface{}, error)

FieldsDeep returns "flattened" items (fields from anonymous inner structs are treated as normal fields)

Example
package main

import (
	"fmt"

	"github.com/oleiade/reflections"
)

type MyStruct struct {
	MyEmbeddedStruct
	FirstField  string `matched:"first tag"`
	SecondField int    `matched:"second tag"`
	ThirdField  string `unmatched:"third tag"`
}

type MyEmbeddedStruct struct {
	EmbeddedField string
}

func main() {
	s := MyStruct{
		FirstField:  "first value",
		SecondField: 2,
		ThirdField:  "third value",
		MyEmbeddedStruct: MyEmbeddedStruct{
			EmbeddedField: "embedded value",
		},
	}

	var structItems map[string]interface{}

	// ItemsDeep will return a field name to
	// field value map, including fields from
	// anonymous embedded structs
	structItems, _ = reflections.ItemsDeep(s)
	fmt.Println(structItems)
}
Output:

func SetField

func SetField(obj interface{}, name string, value interface{}) error

SetField sets the provided obj field with provided value. obj param has to be a pointer to a struct, otherwise it will soundly fail. Provided value type should match with the struct field you're trying to set.

Example
package main

import (
	"log"

	"github.com/oleiade/reflections"
)

type MyStruct struct {
	MyEmbeddedStruct
	FirstField  string `matched:"first tag"`
	SecondField int    `matched:"second tag"`
	ThirdField  string `unmatched:"third tag"`
}

type MyEmbeddedStruct struct {
	EmbeddedField string
}

func main() {
	s := MyStruct{
		FirstField:  "first value",
		SecondField: 2,
		ThirdField:  "third value",
	}

	// In order to be able to set the structure's values,
	// a pointer to it has to be passed to it.
	err := reflections.SetField(&s, "FirstField", "new value")
	if err != nil {
		log.Fatal(err)
	}

	// If you try to set a field's value using the wrong type,
	// an error will be returned
	err = reflections.SetField(&s, "FirstField", 123) // err != nil
	if err != nil {
		log.Fatal(err)
	}
}
Output:

func Tags

func Tags(obj interface{}, key string) (map[string]string, error)

Tags lists the struct tag fields. obj can whether be a structure or pointer to structure.

Example
package main

import (
	"fmt"

	"github.com/oleiade/reflections"
)

type MyStruct struct {
	MyEmbeddedStruct
	FirstField  string `matched:"first tag"`
	SecondField int    `matched:"second tag"`
	ThirdField  string `unmatched:"third tag"`
}

type MyEmbeddedStruct struct {
	EmbeddedField string
}

func main() {
	s := MyStruct{
		FirstField:  "first value",
		SecondField: 2,
		ThirdField:  "third value",
	}

	var structTags map[string]string

	// Tags will return a field name to tag content
	// map. Nota that only field with the tag name
	// you've provided which will be matched.
	// Here structTags will contain:
	// {
	//     "FirstField": "first tag",
	//     "SecondField": "second tag",
	// }
	structTags, _ = reflections.Tags(s, "matched")
	fmt.Println(structTags)
}
Output:

func TagsDeep

func TagsDeep(obj interface{}, key string) (map[string]string, error)

FieldsDeep returns "flattened" tags (fields from anonymous inner structs are treated as normal fields)

Types

This section is empty.

Jump to

Keyboard shortcuts

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