英文:
How to assign an interface variable to the value stored by another
问题
问题描述:
args[0] = ...
更新了args[0]
的值:
package main
import "fmt"
func MyFunc(lambda any) {
myVars := []any {0}
for i := 0; i < 30; i++ {
lambda.(func(...any))(myVars...)
fmt.Println(myVars[0]) // 0, 2, 4, ..., 60 (good)
}
}
func main() {
MyFunc(func(args ...any) {
args[0] = args[0].(int) + 2
})
}
但是当我创建变量v := args[0]
并尝试通过v = ...
来更新args[0]
的值时,Go语言(可以理解)将v
重新赋值为一个新对象,而不是更新args[0]
的值:
package main
import "fmt"
func MyFunc(lambda any) {
myVars := []any {0}
for i := 0; i < 30; i++ {
lambda.(func(...any))(myVars...)
fmt.Println(myVars[0]) // 0, 0, 0, ..., 0 (bad)
}
}
func main() {
MyFunc(func(args ...any) {
v := args[0]
v = v.(int) + 2
})
}
我的问题是:
如何使用v
来更新args[0]
的值?非常感谢任何帮助。
我尝试过的方法:
我不能使用*v = ...
,因为这会导致编译错误"invalid operation: cannot indirect v (variable of type any)"
。
我不能使用v := args[0].(*int); *v = *v + 2;
,因为这会导致运行时错误"panic: interface conversion: interface {} is int, not *int"
。
英文:
Description of the problem:
args[0] = ...
updates args[0]
:
package main
import "fmt"
func MyFunc(lambda any) {
myVars := []any {0}
for i := 0; i < 30; i++ {
lambda.(func(...any))(myVars...)
fmt.Println(myVars[0]) // 0, 2, 4, ..., 60 (good)
}
}
func main() {
MyFunc(func(args ...any) {
args[0] = args[0].(int) + 2
})
}
But when I make variable v := args[0]
and attempt to update the value of args[0]
by doing v = ...
, Go (understandably) reassigns v
to a new object rather than updating the value of args[0]
:
package main
import "fmt"
func MyFunc(lambda any) {
myVars := []any {0}
for i := 0; i < 30; i++ {
lambda.(func(...any))(myVars...)
fmt.Println(myVars[0]) // 0, 0, 0, ..., 0 (bad)
}
}
func main() {
MyFunc(func(args ...any) {
v := args[0]
v = v.(int) + 2
})
}
My question:
How, using v
, can I update args[0]
? Any help will be greatly appreciated.
Things I have tried:
I cannot do *v = ...
, as this yields compiler error "invalid operation: cannot indirect v (variable of type any)"
.
I cannot do v := args[0].(*int); *v = *v + 2;
, as this yields runtime error "panic: interface conversion: interface {} is int, not *int"
.
答案1
得分: 3
你没有正确执行指针操作。请对指针变量v
进行类型断言。首先使用&
获取arg值的地址,然后继续执行你的逻辑。
func main() {
MyFunc(func(args ...any) {
v := &args[0]
*v = (*v).(int) + 2
})
}
英文:
You did not do the pointer operations correctly. Type-assert the pointer variable v
. First take the address of the arg value with &
, then proceed with rest of your logic.
func main() {
MyFunc(func(args ...any) {
v := &args[0]
*v = (*v).(int) + 2
})
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论