fatih / structs

Utilities for Go structs

Home Page:http://godoc.org/github.com/fatih/structs

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Can't set value on embedded struct fields

asdine opened this issue · comments

structs.Field.Set fails when trying to set a value on an embedded struct field because CanSet returns false.

It should not fail since the documentation of CanSet says:

A Value can be changed only if it is addressable and was not obtained by the use of unexported struct fields

Here is an example that you can copy-paste:

package my_test

import (
    "reflect"
    "testing"

    "github.com/fatih/structs"
)

type Base struct {
    ID int
}

type User struct {
    Base
    Name string
}

// This test fails
func TestEmbeddedWithStructs(t *testing.T) {
    u := User{}
    s := structs.New(&u)
    f := s.Field("Base").Field("ID")
    err := f.Set(10)
    if err != nil {
        t.Errorf("Error %v", err)
    }
    if f.Value().(int) != 10 {
        t.Errorf("Value should be equal to 10, got %v", f.Value())
    }
}

// This test works fine
func TestEmbeddedWithReflect(t *testing.T) {
    u := User{}
    s := reflect.ValueOf(&u).Elem()
    f := s.FieldByName("Base").FieldByName("ID")
    if !f.CanSet() {
        t.Error("CanSet should be true")
    }
    f.Set(reflect.ValueOf(10))
    if f.Interface().(int) != 10 {
        t.Errorf("Value should be equal to 10, got %v", f.Interface())
    }
}