Search code examples
variablesgofunc

How to share variables through packages


I'm trying to figure out how can I return a value from a function in a file of a package name to another package. for example let's assume you have

package main

func main(){
   x := 5
   a := res.Test(x)
}
package res

func Test(x int) (y int){
    y := x*2
    return y
}

If I compile it I would get an error: res.Test used as value. Where am I doing wrong, how can I return y to the main/ and other package? thx


Solution

  • At its most basic, a Go packages must be in their own file directory. res goes into ~/go/src/res/.

    // ~/go/src/res/res.go
    package res
    
    func Test(x int) (y int){
        // Note that y is already declared.
        y = x*2
        return y
    }
    

    Then your main.go can import this package.

    package main
    
    import(
        "res"
        "fmt"
    );
    
    func main(){
       x := 5
       a := res.Test(x)
       fmt.Println(a)
    }
    

    See also


    Here's a little further debugging for your specific error.

    Note that the res code you posted should not compile. You should get an error like ./res.go:4:7: no new variables on left side of :=.

    res.Test used as value indicates that res.Test does not return a value, but you tried to use it as one anyway. Your res.Test does have a return value.

    Futhermore, your main.go is not importing res. You should have gotten an error like undefined: res but you didn't.

    This indicates there's another res package floating around somewhere with a Test function with no return value.