Coder Social home page Coder Social logo

oleiade / reflections Goto Github PK

View Code? Open in Web Editor NEW
504.0 15.0 51.0 86 KB

High level abstractions over the Go reflect library

Home Page: https://pkg.go.dev/github.com/oleiade/reflections

License: MIT License

Go 100.00%
go golang reflect reflection runtime types

reflections's Introduction

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.

reflections's People

Contributors

bitdeli-chef avatar cengle avatar chrisbarr avatar oleiade avatar shelnutt2 avatar tcr-ableton avatar tkrajina avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

reflections's Issues

Struct enmbeeded

Is possible to get embeeded struct field for example
struct A {
Person Person
}

struct Person {
fields....
}

I need to get person fields without use direct struct

Git commit overwritten causes builds to fail

Hello,

Thanks for reflections!

We're using this project and had it pinned in Gopkg.lock as follows:

[[projects]]
  digest = "1:c17f50b4ccbba568a6fc10b06a24bb8ac99077470fd48a905759f9914d631dd7"
  name = "github.com/oleiade/reflections"
  packages = ["."]
  pruneopts = "NUT"
  revision = "2b6ec3da648e3e834dc41bad8d9ed7f2dc6a9496"
  version = "v1.0.0"

Earlier today it looks like our builds started failing because the commit 2b6ec3da648e3e834dc41bad8d9ed7f2dc6a9496 no longer exists in this repo. I don't have the full history, but it looks like new commits were force pushed over old commits and and the v1.0.0 tag was updated.

Just a heads up that this will break our builds (and whoever else is using it this way). We can update the lock file on our side, but just letting you know it would be appreciated if new commits are only merged and never rebased so history is preserved, and tags aren't updated.

Thanks again! :)

Enhancement to work with Pointers to Structs?

Am new to golang and working with an app that passes a pointer to an interface type, then uses your reflections library to do GetField, GetFieldTag, and SetField
Having trouble since I want to pass in a pointer to the struct, so I can mutate the object, but the Get* methods want the value not the pointer.
I fiddled with with the GetField and got it to work, but I'm sure the code isn't quite right (see below).
Was wondering if there would be a way for all the Get* methods to be able to identify when a pointer to a struct is passed and then do the right thing

func GetField(obj interface{}, name string) (interface{}, error) {
    var val reflect.Value
    if isPointer(obj) {
        val = reflect.ValueOf(obj).Elem()
    } else if isStruct(obj) {
        val = reflect.ValueOf(obj)
    } else {
        return nil, errors.New("Cannot use GetField on a non-struct interface")
    }

SetField doesn't appear to work

I get the following trace:

`
--- FAIL: TestGetSetAttr (0.00s)
panic: reflect: call of reflect.Value.Elem on struct Value [recovered]
panic: reflect: call of reflect.Value.Elem on struct Value

goroutine 38 [running]:
testing.tRunner.func1(0xc4202544b0)
/usr/lib/go-1.10/src/testing/testing.go:742 +0x29d
panic(0x5d92e0, 0xc4201e9760)
/usr/lib/go-1.10/src/runtime/panic.go:502 +0x229
reflect.Value.Elem(0x5ef860, 0xc4202159e0, 0x99, 0xc4202159e0, 0x99, 0x20)
/usr/lib/go-1.10/src/reflect/value.go:775 +0x1b7
goreposurgeon.SetField(0x5ef860, 0xc4202159e0, 0x618dc0, 0x3, 0x5cb320, 0x64de00, 0x7, 0x61a0b5)
/home/esr/public_html/reposurgeon/src/goreposurgeon/goreposurgeon_test.go:1597 +0x6f
goreposurgeon.TestGetSetAttr(0xc4202544b0)
/home/esr/public_html/reposurgeon/src/goreposurgeon/goreposurgeon_test.go:1644 +0x1fa
testing.tRunner(0xc4202544b0, 0x632770)
/usr/lib/go-1.10/src/testing/testing.go:777 +0xd0
created by testing.(*T).Run
/usr/lib/go-1.10/src/testing/testing.go:824 +0x2e0
FAIL goreposurgeon 0.017s
`

That appears to relate to this line: structValue := reflect.ValueOf(obj).Elem()

If I remove the Elem() call, the function runs to completion but silently fails. e.g the field is not set.

typo

In README.md:

It's API is freely inspired ...

Wrong its. Should be "Its API is inspired..."

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.