I'm working with pointers for the first time and I have what is probably a simple question.
I have two functions main
and other
. If I have a variable in the main
function that I would like to make available in the other
function should I pass it as a parameter or is that defeating the object of pointers?
OPTION 1
func main() {
myVar := "hello world"
other(&myVar)
}
func other(s *string) {
println(s)
}
OPTION 2
func main() {
myVar := "hello world"
other()
}
func other() {
println(*myVar) //Is myVar even accessible here?
}
Not sure why you've got downvoted... The second option will not compile because inside the other function myVar is not present. Every variable has a scope. The variable is only accessible inside it's scope.
(If you like to learn more about the diffrent scopes in go I recommend the following link https://www.golang-book.com/books/web/01-02 - scroll down to scope. It's well explained with a nice visualization.)
To make things a bit clearer, I add some examples:
OPTION 1 - pass the pointer value
This is what you had. But make sure to dereference your pointer to get back the actual string. Your version was printing the pointer itself (mem-address). See my change (*s instead of just s)!
func main() {
myVar := "hello world"
other(&myVar)
}
func other(s *string) {
println(*s)
}
OPTION 2 - pass the variable value
This is probably what you meant with your option 2.
package main
func main() {
myVar := "hello world"
other(myVar)
}
func other(myVar string) {
println(myVar)
}
OPTION 3 - make myVar global
Maybe this is what you wanted to do in your second option. myVar is global here (or as in golang lingo, myVar has a package-level scope), therefore accessible inside the other function.
var myVar = "hello world"
func main() {
other()
}
func other() {
println(myVar)
}
As to your question wether you should pass the value or a pointer to the variable:
In general you pass pointers, if your function needs to be able to edit the value. Also when the variable itself is really big and it would cost time / ressources to pass the value you can pass the pointer which is more efficent.