如何在双向链表(Go语言)中获取元素值的指针。

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

how to get a pointer of element's value in a double-linked list (go-lang)

问题

我想在双向链表中修改一个元素的值,但是我不知道如何获取它的指针,因为元素的值是由Go语言自身定义的nil接口。
据我所知,我必须在获取元素的值之前进行类型断言,像这样:

val, ok := ele.Value.(TYPE)
if ok {
    // 做一些操作...
}

但是如果我只修改val,它将是无效的。
有什么提示吗?

谢谢。

英文:

I want to modify an element's value in a double-linked list, but I don't know how to get its pointer, because element's value is a nil interface defined by go-lang itself.
As far as I know is, I must do a type assertion before get element's value like:

val, ok := ele.Value.(TYPE)
if ok {
    // do something...
}

but if I just modify val it will be useless.
So any hint?

Thanks.

答案1

得分: 1

有两种相当直接的选项。它们都涉及到类型断言,因为你使用了interface{}

你可以将其存储为指针并进行类型断言:

var q interface{}
var i int
q = &i
*(q.(*int)) = 5

你也可以简单地重新赋值:

var q interface{}
q = 5
b := q.(int)
q = 2 * b

我个人认为重新赋值是最合理的选择。如果你在函数中这样做,可能需要返回新值。当然,还有其他改变它的方法,但我认为简单最好。

当然,在实际工作中进行一些检查会更好。

英文:

There are two pretty straight forward options. They're all going to involve type asserting because you're using interface{}

You can store it as a pointer and type assert:

var q interface{}
var i int
q = &i
*(q.(*int)) = 5

You can simply reassign it:

var q interface{}
q = 5
b := q.(int)
q = 2*b

I personally think reassigning it makes the most sense. If you're doing it in a function you probably need to return the new value. I'm sure there are other ways to change it around, but I think simple is best.

Of course in the real work some checking would be nice.

huangapple
  • 本文由 发表于 2016年1月21日 12:13:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/34915290.html
匿名

发表评论

匿名网友

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

确定