Home  >  Article  >  Backend Development  >  What are CanSet, CanAddr?

What are CanSet, CanAddr?

藏色散人
藏色散人forward
2020-10-28 15:32:262876browse

The following column will introduce to you what CanSet and CanAddr are from the golang tutorial column. I hope it will be helpful to friends in need!

What are CanSet, CanAddr?

An article to understand what CanSet and CanAddr are?

What is settable (CanSet)

First of all, we need to clarify that settable is for reflect.Value. To convert an ordinary variable into reflect.Value, you need to use reflect.ValueOf() to convert it first.

So why is there such a "settable" method? For example, the following example:

var x float64 = 3.4v := reflect.ValueOf(x)fmt.Println(v.CanSet()) // false

All function calls in golang are value copies, so when calling reflect.ValueOf, an x ​​has been copied and passed in, and the v obtained here is an x The value of the copy. So at this time, we want to know whether I can set the x variable here through v. We need a method to help us do this: CanSet()

However, it is very obvious that since we are passing a copy of x, the value of x cannot be changed here at all. What is shown here is false.

So what if we pass the address of x into it? Here's an example:

var x float64 = 3.4v := reflect.ValueOf(&x)fmt.Println(v.CanSet()) // false

We pass the address of the x variable to reflect.ValueOf. It should be CanSet. But one thing to note here is that v here points to the pointer of x. So the CanSet method determines whether the pointer of x can be set. Pointers definitely cannot be set, so false is still returned here.

Then what we need to judge from the value of this pointer is whether the element pointed to by this pointer can be set. Fortunately, reflect provides the Elem() method to obtain the "element pointed to by the pointer".

var x float64 = 3.4v := reflect.ValueOf(&x)fmt.Println(v.Elem().CanSet()) // true

Finally returns true. But there is a prerequisite when using Elem(). The value here must be reflect.Value converted from a pointer object. (Or reflect.Value for interface object conversion). This premise is not difficult to understand. If it is an int type, how can it have an element it points to? Therefore, be very careful about this when using Elem, because if this prerequisite is not met, Elem will directly trigger a panic.

After judging whether it can be set, we can make the corresponding settings through the SetXX series of methods.

var x float64 = 3.4v := reflect.ValueOf(&x)if v.Elem().CanSet() {
    v.Elem().SetFloat(7.1)}fmt.Println(x)

More complex types

For complex slice, map, struct, pointer and other methods, I wrote an example:

package mainimport (
    "fmt"
    "reflect")type Foo interface {
    Name() string}type FooStruct struct {
    A string}func (f FooStruct) Name() string {
    return f.A}type FooPointer struct {
    A string}func (f *FooPointer) Name() string {
    return f.A}func main() {
    {
        // slice
        a := []int{1, 2, 3}
        val := reflect.ValueOf(&a)
        val.Elem().SetLen(2)
        val.Elem().Index(0).SetInt(4)
        fmt.Println(a) // [4,2]
    }
    {
        // map
        a := map[int]string{
            1: "foo1",
            2: "foo2",
        }
        val := reflect.ValueOf(&a)
        key3 := reflect.ValueOf(3)
        val3 := reflect.ValueOf("foo3")
        val.Elem().SetMapIndex(key3, val3)
        fmt.Println(val) // &map[1:foo1 2:foo2 3:foo3]
    }
    {
        // map
        a := map[int]string{
            1: "foo1",
            2: "foo2",
        }
        val := reflect.ValueOf(a)
        key3 := reflect.ValueOf(3)
        val3 := reflect.ValueOf("foo3")
        val.SetMapIndex(key3, val3)
        fmt.Println(val) // &map[1:foo1 2:foo2 3:foo3]
    }
    {
        // struct
        a := FooStruct{}
        val := reflect.ValueOf(&a)
        val.Elem().FieldByName("A").SetString("foo2")
        fmt.Println(a) // {foo2}
    }
    {
        // pointer
        a := &FooPointer{}
        val := reflect.ValueOf(a)
        val.Elem().FieldByName("A").SetString("foo2")
        fmt.Println(a) //&{foo2}
    }}

If you can understand the above example, then you basically understand the CanSet method.

You can pay special attention to the fact that map and pointer do not need to pass the pointer to reflect.ValueOf when they are modified. Because they are pointers themselves.

So when calling reflect.ValueOf, we must be very clear about the underlying structure of the variable we want to pass. For example, map actually transfers a pointer, and we don't need to point it anymore. As for slice, what is actually passed is a SliceHeader structure. When we modify Slice, we must pass the pointer of SliceHeader. This is something we often need to pay attention to.

CanAddr

You can see in the reflect package that in addition to CanSet, there is also a CanAddr method. What's the difference between the two of them?

The difference between the CanAddr method and the CanSet method is that for some private fields in the structure, we can get its address, but we cannot set it.

For example, the following example:

package mainimport (
    "fmt"
    "reflect")type FooStruct struct {
    A string
    b int}func main() {
    {
        // struct
        a := FooStruct{}
        val := reflect.ValueOf(&a)
        fmt.Println(val.Elem().FieldByName("b").CanSet())  // false
        fmt.Println(val.Elem().FieldByName("b").CanAddr()) // true
    }}

So, CanAddr is a necessary and insufficient condition for CanSet. A Value if CanAddr, not necessarily CanSet. But if a variable canSet, it must be CanAddr.

Source code

Assuming we want to implement this Value element CanSet or CanAddr, we will most likely use the mark bit mark. This is indeed the case.

Let’s take a look at the structure of Value first:

type Value struct {
    typ *rtype
    ptr unsafe.Pointer
    flag}

What should be noted here is that it is a nested structure with a flag nested inside it, and the flag itself is a uintptr.

type flag uintptr

This flag is very important. It can express not only the type of the value, but also some meta-information (such as whether it is addressable, etc.). Although flag is of uint type, it is represented by bit marks.

First of all, it needs to represent the type. There are 27 types in golang:

const (
    Invalid Kind = iota
    Bool
    Int
    Int8
    Int16
    Int32
    Int64
    Uint
    Uint8
    Uint16
    Uint32
    Uint64
    Uintptr
    Float32
    Float64
    Complex64
    Complex128
    Array
    Chan
    Func
    Interface
    Map
    Ptr
    Slice
    String
    Struct
    UnsafePointer)

所以使用5位(2^5-1=63)就足够放这么多类型了。所以 flag 的低5位是结构类型。

第六位 flagStickyRO: 标记是否是结构体内部私有属性
第七位 flagEmbedR0: 标记是否是嵌套结构体内部私有属性
第八位 flagIndir: 标记 value 的ptr是否是保存了一个指针
第九位 flagAddr: 标记这个 value 是否可寻址
第十位 flagMethod: 标记 value 是个匿名函数

What are CanSet, CanAddr?

其中比较不好理解的就是 flagStickyRO,flagEmbedR0

看下面这个例子:

type FooStruct struct {
    A string
    b int}type BarStruct struct {
    FooStruct}{
        b := BarStruct{}
        val := reflect.ValueOf(&b)
        c := val.Elem().FieldByName("b")
        fmt.Println(c.CanAddr())}

这个例子中的 c 的 flagEmbedR0 标记位就是1了。

所以我们再回去看 CanSet 和 CanAddr 方法

func (v Value) CanAddr() bool {
    return v.flag&flagAddr != 0}func (v Value) CanSet() bool {
    return v.flag&(flagAddr|flagRO) == flagAddr}

他们的方法就是把 value 的 flag 和 flagAddr 或者 flagRO (flagStickyRO,flagEmbedR0) 做“与”操作。

而他们的区别就是是否判断 flagRO 的两个位。所以他们的不同换句话说就是“判断这个 Value 是否是私有属性”,私有属性是只读的。不能Set。

应用

在开发 collection (https://github.com/jianfengye/collection)库的过程中,我就用到这么一个方法。我希望设计一个方法 func (arr *ObjPointCollection) ToObjs(objs interface{}) error,这个方法能将 ObjPointCollection 中的 objs reflect.Value 设置为参数 objs 中。

func (arr *ObjPointCollection) ToObjs(objs interface{}) error {
    arr.mustNotBeBaseType()

    objVal := reflect.ValueOf(objs)
    if objVal.Elem().CanSet() {
        objVal.Elem().Set(arr.objs)
        return nil    }
    return errors.New("element should be can set")}

使用方法:

func TestObjPointCollection_ToObjs(t *testing.T) {
    a1 := &Foo{A: "a1", B: 1}
    a2 := &Foo{A: "a2", B: 2}
    a3 := &Foo{A: "a3", B: 3}

    bArr := []*Foo{}
    objColl := NewObjPointCollection([]*Foo{a1, a2, a3})
    err := objColl.ToObjs(&bArr)
    if err != nil {
        t.Fatal(err)
    }
    if len(bArr) != 3 {
        t.Fatal("toObjs error len")
    }
    if bArr[1].A != "a2" {
        t.Fatal("toObjs error copy")
    }}

总结

CanAddr 和 CanSet 刚接触的时候是会有一些懵逼,还是需要稍微理解下 reflect.Value 的 flag 就能完全理解了。

The above is the detailed content of What are CanSet, CanAddr?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:learnku.com. If there is any infringement, please contact admin@php.cn delete