Variables and Types in Go: Understanding the Basics
In Go, variables are defined using the var
keyword. You can define variables at the package level or inside a function.
At the package level, a variable is visible across all the files that make up the package. On the other hand, a variable defined inside a function is only visible within that function.
When you define a variable using var
, Go automatically infers its type based on the assigned value. For example:
1 | var age = 20 |
In this case, Go determines that the type of the variable age
is int
.
There are various types available in Go, including int
, string
, and bool
. You can also declare variables without an initial value by specifying the type explicitly:
1 | var age int |
When you already know the value of a variable, you can use the short variable declaration (:=
) to declare and assign the value in a single line:
1 | age := 10 |
Variable names in Go can contain letters, digits, and underscores (_
), but they must start with a character or underscore. Remember that variable names are case-sensitive.
If a variable’s value needs to be changed during the program’s execution, you can use the assignment operator (=
) to assign a new value:
1 | var age int |
For variables that never change, you can declare them as constants using the const
keyword:
1 | const age = 10 |
You can also declare and initialize multiple variables on a single line:
1 | var age, name = 10, "Roger" |
It’s important to note that declaring variables that are not used in the program will result in an error, and the program will not compile.
Go is a typed language, which means you can explicitly specify the type when declaring a variable using var
, or you can let Go infer the type from the assigned value.
The basic types in Go include integers (int
, int8
, int16
, int32
, rune
, int64
, uint
, uintptr
, uint8
, uint16
, uint64
), floats (float32
, float64
), complex types (complex64
, complex128
), byte (byte
), strings (string
), and booleans (bool
).
Typically, you’ll use int
for integers, float64
for decimal numbers, string
for text, and bool
for boolean values. The specific type you choose may depend on optimization needs or specific requirements.
Remember that value types in Go are passed by value to functions, meaning a copy of the value is passed, not the original variable.
Tags: Go programming, Go variables, Go types, Go basics