Home > Back-end >  How to assign an interface variable to the object referenced
How to assign an interface variable to the object referenced

Time:09-01

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".

CodePudding user response:

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
    })
}

Go playground

  • Related