Where you define a variable is very important depending on where you want to use it. The range of places that you are allowed to use the variable is called thescope
of the variable.
According to the language specification “Go is lexically scoped using blocks”. For us mere mortals, this means that you can use a variable from within the nearest curly braces ({}
), called a “block”. Let's look at a few examples:
func main() {
x:= "Hi"
fmt.Println(x) // Hi
}
This works because x is defined within the same block (curly braces) as it is being used. If we were to add another function to our program below main
it would not have access to x:
func f() {
fmt.Println(x) // this would error
}
However, we could define the variable in the global scope of the program and it would be available to both functions:
var x = "Hi"
func main() {
fmt.Println(x) // Hi
}
func f() {
fmt.Println(x) // Hi
}
Global variables should be used with caution since variables are mutable in Go. This means that you could define a variable in the global scope, and have a function change this variable, making your program more difficult to understand. You will more often see constants (const
) rather than variables defined in global scope for this reason.
Local scope will take preference over the global variables, so you could redefine x within one of your functions to affect only that local scope:
var x = "Hi"
func main() {
x:= "Hello"
fmt.Println(x) // Hello
}
func f() {
fmt.Println(x) // Hi
}
Again, note the difference between what you could do and what you should do. Think about the readability of your code and make it as easy to understand as possible.
Self taught software developer with 12 years experience excelling at JavaScript/Typescript, React, Node and AWS.
I love learning and teaching and have mentored several junior developers over my career. I find teaching is one of the best ways to solidify your own learning, so in the past few years I've been maintaining a technical blog where I write about some things that I've been learning.
I'm passionate about building a teams culture and processes to make it efficient and satisfying to work in. In many roles I have improved the quality and reliability of the code base by introducing or improving the continuous integration pipeline to include quality gates.