英文:
How to access list.Element.Value's own property in Golang?
问题
使用container/list
,可以轻松地管理列出的元素,并按顺序访问每个元素。
但是,似乎无法访问每个元素的自定义类型派生的属性,因为element.Value
的类型是interface{}
。
for p := members.Front(); p != nil; p = p.Next() {
fmt.Printf("This is Person -> %+v\n", p.Value)
fmt.Printf("This is also `Person` -> %T\n\n", p.Value)
// fmt.Printf("But cannnot access Person.Name %s\n", p.Value.Name)
}
(完整代码在这里:http://play.golang.org/p/AMWqdPymHq)
如何访问element.Value
的自有属性,或者在构造列表对象时应用类型?
英文:
Using container/list
, it's easy to make object managing listed elements, and access each element sequentially.
But it seems each element.Value cannot allow to access it's own property derived from user defined type, because the type of element.Value
is interface{}
for p := members.Front(); p != nil; p = p.Next() {
fmt.Printf("This is Person -> %+v\n", p.Value)
fmt.Printf("This is also `Person` -> %T\n\n", p.Value)
// fmt.Printf("But cannnot access Person.Name %s\n", p.Value.Name)
}
(whole code here: http://play.golang.org/p/AMWqdPymHq)
How can I access element.Value's own property, or apply the type while constructing list object?
答案1
得分: 5
如果你知道列表包含的是Person
值,你可以使用类型断言从interface{}
变量中检索该值:
person := p.Value.(Person)
现在你可以完全访问该值并访问其字段。请注意,person
是存储在p.Value
中的值的副本,因此修改person
不会修改列表中的值项。你可以通过将修改后的person
赋值回p.Value
或在列表中存储*Person
指针来解决这个问题。
如果列表项不包含Person
值,上述代码将引发恐慌。如果你知道列表将始终包含该类型的值,那么这是可以接受的。否则,你可以使用两个返回值的类型断言语法:
person, ok := p.Value.(Person)
如果类型不匹配,它将将ok
设置为false
。对于更复杂的情况,你还可以使用type switch。
英文:
If you know that the list contains Person
values, you can retrieve that value from the interface{}
variable using a type assertion:
person := p.Value.(Person)
You now have full access to the value and can access its fields. Note that person
is a copy of the value stored in p.Value
, so modifying person
will not modify the value item in the list. You can work around this by either (a) assigning the modified person
back to p.Value
or (b) store *Person
pointers in the list.
If list item does not contain a Person
value, the above code will panic. That's fine if you know the list will always contain values of that type. Otherwise, you can use the two-return type assertion syntax:
person, ok := p.Value.(Person)
Which will instead set ok
to false
if the type doesn't match. For more complex cases, you can also use a type switch.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论