10. Variables
Naming memory locations

What are Variables?

Variables are named memory locations, that are used to refer to data in our program. General format for variable is Go is: var name type = expression
Variable names must start with letter and can contain letter and number.

Declaring variables

Variables are declared using varkeyword. Before using variables, they need to be declared. For declaring variables:
  • Use the var keyword.
  • Write a variable name.
  • Write the variable type.
  • Optionally, assign value using equals =
main.go
1
func main() {
2
var s string
3
s = "sumit"
4
var i, j, k int
5
}
Copied!
Multiple variables of same type can be declared using comma separation in name. All declared variables should be used.Variable name can not be reserved keywords.
keywords
1
break default func
2
interface select case
3
defer go map
4
struct chan else
5
goto package switch
6
const fallthrough if
7
range type continue
8
for import return
9
var
Copied!

Short variable declaration

Short variable declaration may be used to declare and initialize local variables.It takes the form name := expression.Below declarations are one and the same
main.go
1
func main() {
2
var s string
3
s = "hello, world!"
4
t := "hello, world!"
5
6
var i int
7
i = 42
8
j := 42
9
}
Copied!

Variable Scope

Variables are visible only with the scope they are declared. We can access the variable so long as it’s in scope, but once a variable is no longer in scope, attempts to access it will report an error. Scope is defined by braces {}

From the Docs

Effective Go - The Go Programming Language
Effective Go
Last modified 2yr ago