英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论