Go variables and constants
2 min readAug 13, 2023
Go is a statically typed programming language, so we must declare variable type every time we use it.
There are three ways to declare variables.
- First, declaring variables with datatype. In this case, we are assigning the datatype explicitly.
package main
import "fmt"
func main() {
var name string
var lastname string = "Racer"
var age int = 20
name = "Speed"
fmt.Printf("Name : %s, Type : %T\n", name, name)
fmt.Printf("Lastname : %s, Type : %T\n", lastname, lastname)
fmt.Printf("Age: %d, Type: %T\n", age, age)
}
Output:
Name : Speed, Type : string
Lastname : Racer, Type : string
Age: 20, Type: int
- Second, using only var, and we don’t specify a datatype for variables; the type will be implicitly taken from the assigned value.
package main
import "fmt"
func main() {
var name = "Speed"
var lastname= "Racer"
var age= 20
fmt.Printf("Name : %s, Type : %T\n", name, name)
fmt.Printf("Lastname : %s, Type : %T\n", lastname, lastname)
fmt.Printf("Age: %d, Type: %T\n", age, age)
}
The output will be the same as above.
- Third, the shorthand syntax. We use := to declare the variable and assign the datatype implicitly. The data type is obtained depending on the value assigned.
package main
import "fmt"
func main() {
name := "Speed"
lastname := "Racer"
age := 20
fmt.Printf("Name : %s, Type : %T\n", name, name)
fmt.Printf("Lastname : %s, Type : %T\n", lastname, lastname)
fmt.Printf("Age: %d, Type: %T\n", age, age)
}
Zero values
Every time we declare a variable without assigning a value, the value of those variables will be set to zero-value according to the datatype used.
package main
import "fmt"
func main() {
var name string
var lastname string
var age int
fmt.Printf("Name : %s, Type : %T\n", name, name)
fmt.Printf("Lastname : %s, Type : %T\n", lastname, lastname)
fmt.Printf("Age: %d, Type: %T\n", age, age)
}
Output:
Name : , Type : string
Lastname : , Type : string
Age: 0, Type: int
String variables: name and lastname will be “”, and age (int — 8 bits) will be 0.
Constants
To declare constants in Go, we use the keyword const. Constants obtain their datatype depending on the assigned value.
package main
import "fmt"
const PI = 3.14
const PREFIX = "variable-"
func main() {
fmt.Printf("PI = %v, Type : %T\n", PI, PI)
fmt.Printf("PREFIX = %v, Type : %T\n", PREFIX, PREFIX)
}
Output:
PI = 3.14, Type : float64
PREFIX = variable-, Type : string