How to access list.Element.Value's own property in Golang?

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

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.

huangapple
  • 本文由 发表于 2014年4月11日 13:52:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/23004515.html
匿名

发表评论

匿名网友

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

确定