search
HomeBackend DevelopmentGolangWhat are CanSet, CanAddr?

What are CanSet, CanAddr?

Oct 28, 2020 pm 03:32 PM
gogolang

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. If there is any infringement, please contact admin@php.cn delete
Golang's Impact: Speed, Efficiency, and SimplicityGolang's Impact: Speed, Efficiency, and SimplicityApr 14, 2025 am 12:11 AM

Goimpactsdevelopmentpositivelythroughspeed,efficiency,andsimplicity.1)Speed:Gocompilesquicklyandrunsefficiently,idealforlargeprojects.2)Efficiency:Itscomprehensivestandardlibraryreducesexternaldependencies,enhancingdevelopmentefficiency.3)Simplicity:

C   and Golang: When Performance is CrucialC and Golang: When Performance is CrucialApr 13, 2025 am 12:11 AM

C is more suitable for scenarios where direct control of hardware resources and high performance optimization is required, while Golang is more suitable for scenarios where rapid development and high concurrency processing are required. 1.C's advantage lies in its close to hardware characteristics and high optimization capabilities, which are suitable for high-performance needs such as game development. 2.Golang's advantage lies in its concise syntax and natural concurrency support, which is suitable for high concurrency service development.

Golang in Action: Real-World Examples and ApplicationsGolang in Action: Real-World Examples and ApplicationsApr 12, 2025 am 12:11 AM

Golang excels in practical applications and is known for its simplicity, efficiency and concurrency. 1) Concurrent programming is implemented through Goroutines and Channels, 2) Flexible code is written using interfaces and polymorphisms, 3) Simplify network programming with net/http packages, 4) Build efficient concurrent crawlers, 5) Debugging and optimizing through tools and best practices.

Golang: The Go Programming Language ExplainedGolang: The Go Programming Language ExplainedApr 10, 2025 am 11:18 AM

The core features of Go include garbage collection, static linking and concurrency support. 1. The concurrency model of Go language realizes efficient concurrent programming through goroutine and channel. 2. Interfaces and polymorphisms are implemented through interface methods, so that different types can be processed in a unified manner. 3. The basic usage demonstrates the efficiency of function definition and call. 4. In advanced usage, slices provide powerful functions of dynamic resizing. 5. Common errors such as race conditions can be detected and resolved through getest-race. 6. Performance optimization Reuse objects through sync.Pool to reduce garbage collection pressure.

Golang's Purpose: Building Efficient and Scalable SystemsGolang's Purpose: Building Efficient and Scalable SystemsApr 09, 2025 pm 05:17 PM

Go language performs well in building efficient and scalable systems. Its advantages include: 1. High performance: compiled into machine code, fast running speed; 2. Concurrent programming: simplify multitasking through goroutines and channels; 3. Simplicity: concise syntax, reducing learning and maintenance costs; 4. Cross-platform: supports cross-platform compilation, easy deployment.

Why do the results of ORDER BY statements in SQL sorting sometimes seem random?Why do the results of ORDER BY statements in SQL sorting sometimes seem random?Apr 02, 2025 pm 05:24 PM

Confused about the sorting of SQL query results. In the process of learning SQL, you often encounter some confusing problems. Recently, the author is reading "MICK-SQL Basics"...

Is technology stack convergence just a process of technology stack selection?Is technology stack convergence just a process of technology stack selection?Apr 02, 2025 pm 05:21 PM

The relationship between technology stack convergence and technology selection In software development, the selection and management of technology stacks are a very critical issue. Recently, some readers have proposed...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment