Home > front end >  How to make nil interface to struct in golang
How to make nil interface to struct in golang

Time:07-24

I'm new in Golang. I executed the code below. I get empty humans array in the end. What should I do in func F?

For testing(monkeypatch) sake. I have to follow the way how the origin func is called.

package main

import (
    "fmt"
)

type Human struct {
    Name string
}

type Cat struct {
    Name string
}

func F(arr interface{}) {
    switch arr.(type) {
    case *[]*Human:
        arr = &[]*Human{{Name: "abc"}}
        arr = arr.(*[]*Human)

    case *[]*Cat:
        arr = &[]*Cat{{Name: "meow"}}
        arr = arr.(*[]*Cat)
    }

}

func main() {

    var humans []*Human
    F(&humans)
    fmt.Println(humans)

    var cats []*Cat
    F(&cats)
    fmt.Println(cats)
}

CodePudding user response:

The answer, and the main issue cause as well, is that Go always uses pass by value (or copy of the value) when arguments are passed around to function or assigned to variables.

Your function F takes an arr argument:

func F(arr interface{}) {
    //...
}

When called from your main function, you are passing an []*Human pointer as an argument, which values will be copied and fed to your function F for execution.

Going back to your function F body, the arr will be having the same value passed by main, which happens to be the address to the original []*Human struct. Upon assigning a new value to arr:

func F(arr interface{}) {
    switch arr.(type) {
    case *[]*Human:
        arr = &[]*Human{{Name: "abc"}}
        // ...
    }
}

You are assigning a new value to the local arr variable and not to the original pointer, which remains, indeed, unchanged.

To update the value toward which the argument pointer is referring to, you should used the dereferrence symbol:

func F(arr interface{}) { switch arr := arr.(type) { case *[]*Human: *arr = []*Human{&Human{Name: "abc"}} fmt.Println(arr) // ... } }

Note the switch arr := arr.(type) statement which creates a new arr variable (shadowing the argument arr) with the interface dynamic type to be able to assign the proper value to it.

  •  Tags:  
  • go
  • Related