通过fmt.Sscan设置结构的值

huangapple go评论75阅读模式
英文:

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}

https://play.golang.org/p/6_4DjiFZB2

huangapple
  • 本文由 发表于 2017年9月17日 23:37:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/46265834.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定