Go variable declaration¶
In Go, variables are used to hold data within a program.^[400-devops__09-Scripting-Language__golang__introduction__readme.md] Because variables consume memory space, it is standard practice to keep their usage minimal and efficient^[400-devops__09-Scripting-Language__golang__introduction__readme.md].
Declaration Syntax¶
Go provides two primary ways to declare variables within a function, distinguished by the use of the var keyword versus the short assignment operator :=^[400-devops__09-Scripting-Language__golang__introduction__readme.md].
var keyword¶
The var keyword is used to explicitly declare a variable.^[400-devops__09-Scripting-Language__golang__introduction__readme.md] This method assigns a value to the variable at the time of declaration.
var firstName = "Marcel"
Short declaration operator (:=)¶
For concise code, Go allows variables to be declared and initialized using the := operator^[400-devops__09-Scripting-Language__golang__introduction__readme.md]. This syntax infers the type based on the assigned value.
lastName := "Dempers"
Variable Assignment¶
Once declared, variables can hold values to be used in operations or returned by functions^[400-devops__09-Scripting-Language__golang__introduction__readme.md]. While values can be assigned to named variables (e.g., fullName), it is also possible to return the result of a computation or a literal directly without declaring an intermediate variable^[400-devops__09-Scripting-Language__golang__introduction__readme.md].
fullName := firstName + " " + lastName
// Direct computation is also valid
return firstName + " " + lastName
Related concepts¶
- [[Go functions]]
- [[Go control flow]]
Sources¶
^[400-devops__09-Scripting-Language__golang__introduction__readme.md]