Calling a variable from another function in go

Solution 1:

It's not possible to print the value of the A variable declared in the Smile() function from main().

And the main reason for that is that the variable A only exists if code execution enters the Smile() function, more precisely reaches the A variable declaration. In your example this never happens.

And even if in some other example this happens (e.g. Smile() is called), an application may have multiple goroutines, and multiple of them may be executing Smile() at the same time, resulting in the app having multiple A variables, independent from each other. In this situation, which would A in main() refer to?

Go is lexically scoped using blocks. This means the variable A declared inside Smile() is only accessible from Smile(), the main() function cannot refer to it. If you need such "sharing", you must define A outside of Smile(). If both Smile() and main() needs to access it, you have to make it either a global variable, or you have to pass it to the functions that need it.

Making it a global variable, this is how it could look like:

var a int

func smile() {
    a = 5
    fmt.Println("a in smile():", a)
}

func main() {
    smile()
    fmt.Println("a in main():", a)
}

This outputs (try it on the Go Playground):

a in smile(): 5
a in main(): 5

Declaring it local in main() and passing it to smile(), this is how it could look like:

func smile(a int) {
    fmt.Println("a in smile():", a)
}

func main() {
    a := 5
    fmt.Println("a in main():", a)
    smile(a)
}

Output (try it on the Go Playground):

a in main(): 5
a in smile(): 5

Solution 2:

The best way is, https://godoc.org/golang.org/x/tools/go/pointer

Pointers

Ex:

func getCar() {
   car := Vehicles.Car{}
   setModel(&car)
   // model ("BMW") will be available here
}

func setModel(car *Vehicles.Car) {
   car.Model = "BMW"
}