英文:
Setting value of the structure via fmt.Sscan
问题
我想要在map[string]string和自定义的Go结构之间同步状态,并得出结论,最简单的解析方法是使用fmt.Sscan来处理字段。
不幸的是,直接的方法不起作用(playground):
var S struct{ I int }
f := reflect.Indirect(reflect.ValueOf(&S)).Field(0)
fmt.Sscan("10", f.Interface())
fmt.Println(S) // {0}
然而,引入一个中间值并使用Set()可以解决这个问题:
nv := reflect.New(f.Type())
fmt.Sscan("10", nv.Interface())
f.Set(reflect.Indirect(nv))
fmt.Println(S) // {10}
我想知道为什么第一种方法不起作用。Interface()难道不返回一个可以用来更改其值的字段引用吗?
英文:
I want to synchronize state between map[string]string and custom Go structure and came to a conclusion that simplest way to parse it is to use fmt.Sscan for fields.
Unfortunately, direct approach is not working (playground):
var S struct{ I int }
f := reflect.Indirect(reflect.ValueOf(&S)).Field(0)
fmt.Sscan("10", f.Interface())
fmt.Println(S) // {0}
Introducing an intermediate value and using Set(), however, solves the issue:
nv := reflect.New(f.Type())
fmt.Sscan("10", nv.Interface())
f.Set(reflect.Indirect(nv))
fmt.Println(S) // {10}
I wonder why the first approach didn't work. Isn't Interface() returns a kind of reference to a field which can be used to change its value?
答案1
得分: 2
Interface()方法返回的是值,而不是值的引用。通过调用Addr()方法获取字段的地址,直接将其扫描到字段中:
var S struct{ I int }
f := reflect.Indirect(reflect.ValueOf(&S)).Field(0)
fmt.Sscan("10", f.Addr().Interface())
fmt.Println(S) // {10}
链接:https://play.golang.org/p/6_4DjiFZB2
英文:
The Interface() method returns the value, not a reference to the value. Take the address (by calling Addr()) of the field to scan directly to the field:
var S struct{ I int }
f := reflect.Indirect(reflect.ValueOf(&S)).Field(0)
fmt.Sscan("10", f.Addr().Interface())
fmt.Println(S) // {0}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论