-3

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

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
wecandoit
  • 37
  • 6
  • "If I compile it I would get an error." What error are you getting, and how are you compiling it? Where are these files in relation to each other? – Schwern Mar 04 '20 at 23:37
  • this looks like valid function usage - but main will fail to compile since the variable `a` is set but not referenced anywhere after being set. – colm.anseo Mar 04 '20 at 23:42
  • @colminator how can i solve it – wecandoit Mar 04 '20 at 23:43
  • @Schwern I updated the post with the error – wecandoit Mar 04 '20 at 23:45
  • @wecandoit You should not have gotten that error with the posted code. I've added some speculation why in my answer, but double check you posted the real code. – Schwern Mar 04 '20 at 23:54
  • Sure your package function returns something? [See](https://stackoverflow.com/questions/12561162/used-as-value-in-function-call) – colm.anseo Mar 04 '20 at 23:54
  • 1
    Please take the Tour of Go (which describes how packages are used) and How to Write Go code (which describes how packages are written). – Volker Mar 05 '20 at 04:36

1 Answers1

1

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.

Schwern
  • 153,029
  • 25
  • 195
  • 336
  • I like your thinking but if there was another `res.Test` you would expect the error: `res.Test used as value, but it returns nothing` @wecandoit your comments and question are inconsistent. You need to post a small example with the exact code and error message. – AJR Mar 05 '20 at 07:18