如何将一个接口变量分配给另一个存储的值?

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

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 &quot;fmt&quot;

func MyFunc(lambda any) {
	myVars := []any {0}
	for i := 0; i &lt; 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 &quot;fmt&quot;

func MyFunc(lambda any) {
	myVars := []any {0}
	for i := 0; i &lt; 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 &quot;invalid operation: cannot indirect v (variable of type any)&quot;.

I cannot do v := args[0].(*int); *v = *v + 2;, as this yields runtime error &quot;panic: interface conversion: interface {} is int, not *int&quot;.

答案1

得分: 3

你没有正确执行指针操作。请对指针变量v进行类型断言。首先使用&获取arg值的地址,然后继续执行你的逻辑。

func main() {
	MyFunc(func(args ...any) {
		v := &args[0]
		*v = (*v).(int) + 2
	})
}

Go playground

英文:

You did not do the pointer operations correctly. Type-assert the pointer variable v. First take the address of the arg value with &amp;, then proceed with rest of your logic.

func main() {
	MyFunc(func(args ...any) {
		v := &amp;args[0]
		*v = (*v).(int) + 2
	})
}

Go playground

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

发表评论

匿名网友

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

确定