Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to assign an interface variable to the object referenced

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]:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading