• Stars
    star
    498
  • Rank 88,494 (Top 2 %)
  • Language
    Go
  • License
    MIT License
  • Created over 11 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

High level abstractions over the Go reflect library

Reflections

MIT License Build Status Go Documentation Go Report Card Go Version

The reflections library provides high-level abstractions on top of the go language standard reflect library.

In practice, the reflect library's API proves somewhat low-level and un-intuitive. Using it can turn out pretty complex, daunting, and scary, especially when doing simple things like accessing a structure field value, a field tag, etc.

The reflections package aims to make developers' life easier when it comes to introspect struct values at runtime. Its API takes inspiration in the python language's getattr, setattr, and hasattr set of methods and provides simplified access to structure fields and tags.

Documentation

Head to the documentation to get more details on the library's API.

Usage

GetField

GetField returns the content of a structure field. For example, it proves beneficial when you want to iterate over struct-specific field values. You can provide GetField a structure or a pointer to a struct as the 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. You can use it to operate type assertion over a structure field at runtime. You can provide GetFieldKind a structure or a pointer to structure as the 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. You can use it to operate type assertion over a structure field at runtime. You can provide GetFieldType a structure or a pointer to structure as the 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 provide GetFieldTag a structure or a pointer to structure as the 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 the structure. You can provide HasField a struct or a pointer to a struct as the 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 structure field names so that you can access or update them later. You can provide Fields with a struct or a pointer to a struct as the 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 the values map. You can provide Items with a struct or a pointer to structure as the 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 provide Tags with a struct or a pointer to a struct as the 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. N.B that only field with the tag name
// you've provided will be matched.
// Here structTags will contain:
// {
// "FirstField": "first tag",
// "SecondField": "second tag",
// }
structTags, _ = reflections.Tags(s, "matched")

SetField

SetField updates a structure's field value with the one provided. Note that you can't set un-exported fields and that the field and value types must match.

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

//To be able to set the structure's values,
// it must be passed as a pointer.
_ := 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

GetFieldNameByTagValue

GetFieldNameByTagValue looks up a field with a matching {tagKey}:"{tagValue}" tag in the provided obj item. If obj is not a struct, nor a pointer, or it does not have a field tagged with the tagKey, and the matching tagValue, this function returns an error.

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

// Getting field name from external source as json would be a headache to convert it manually, 
// so we get it directly from struct tag
// returns fieldName = "FirstField"
fieldName, _ = reflections.GetFieldNameByTagValue(s, "matched", "first tag");

// later we can do GetField(s, fieldName)

Important notes

  • Un-exported fields can't be accessed nor set using the reflections library. The Go lang standard reflect library intentionally prohibits un-exported fields values access or modifications.

Contribute

  • Check for open issues or open a new 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 showing that the bug was fixed or 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.

More Repositories

1

trousseau

File based encrypted key-value store
Go
954
star
2

lane

Generic PriorityQueues, Queues, Stacks, and Deque data structures for Go
Go
847
star
3

Elevator

Elevator is an open source, on-disk key-value store. Provides high-performance bulk read-write operations over very large datasets while exposing a simple and efficient API.
Python
71
star
4

motus

Dead simple password generator
Rust
60
star
5

durations

A Python durations parsing library
Python
25
star
6

etcaetera

Manage multiple configuration sources in a single place
Python
24
star
7

gomme

Parser combinator library for Go
Go
18
star
8

mymy

Gather information about your system quickly, intuitively, and easily.
Rust
13
star
9

py-elevator

py-elevator is a python client for Elevator, a Key-Value store written in Python and based on levelDB, allows high performance on-disk bulk read/write.
Python
13
star
10

elm-maestro

Elm music theory library
Elm
11
star
11

serrure

A encryption/decryption toolkit library for golang
Go
10
star
12

jackdauer

Use this Rust crate to easily parse various time formats to durations.
Rust
7
star
13

lhotse

Tiny HTTP server with controllable performance.
Go
6
star
14

k6-support

A full-fledged local k6 ecosystem a docker-compose up away
JavaScript
6
star
15

freebase4neo

Clojure util to setup a Freebase endpoint in Neo4j
Clojure
4
star
16

go-dynamic-array

Dynamic arrays Go lang implementation
Go
4
star
17

stamp

A simple license applier python script. Allows user to easily apply a specified license to some files.
Python
4
star
18

patron

A minimalist template system for Ableton Live
JavaScript
3
star
19

Happening

Go
3
star
20

Hurdles

A simple and yet powerful python benchmark framework. Write unit benchs just like you'd write unit tests.
Python
3
star
21

docker-localshop

Localshop pypi repository docker container builder
Python
3
star
22

Ash

Another Shell
C
2
star
23

Fridge

Ftp bridge over S3, controllable via RestFul api
Python
2
star
24

Butcher

Slice fat files into shinny slim ones in just a command
Go
2
star
25

xk6-exec

A k6 extension to execute shell commands from your k6 scripts
Go
2
star
26

Garbo

An automated plant monitoring and watering system for your garden
C++
1
star
27

Learn-unix-the-hacker-way-fr

Learn Unix, the hacker way
1
star
28

tempura

Temporary files creation and manipulation helpers for Go
Go
1
star
29

Paon

A simple Snake C++ game, including a two players "Tron mode".
1
star