Variables and Constants
Overview
Variables let a Go program store values and reuse them in calculations.
The example used in this page is a small investment calculator with hardcoded values.
Create Variables
Use var to create a variable.
var investmentAmount = 1000
var returnRate = 0.05
var years = 10
var inflationRate = 0.02
Each variable stores a value.
investmentAmountstores the starting investment amountreturnRatestores the expected yearly return rateyearsstores the investment durationinflationRatestores the expected yearly inflation rate
Go variables should use clear names. For multi-word names, Go commonly uses camel case.
Note: A variable should be used after it is declared. If you declare a variable and never use it, Go reports an error.
Variable Scope
Variables can be declared inside a function or outside a function.
-
Inside a function (most common)
Declare variables inside a function if they are only used there.
package mainimport "fmt"func main() {var name = "Alice"fmt.Println(name)} -
Outside a function (package-level variable)
Declare variables outside functions if they need to be shared across multiple functions.
package mainimport "fmt"var greeting = "Hello"func main() {printGreeting()}func printGreeting() {fmt.Println(greeting)}Note that when you declare a variable outside a function, you have to use the
varkeyword. You cannot use the:=syntax for package-level variables.This will NOT work:
greeting := "Hello"