Variables & Constants

Duration: 10 min  •  Difficulty: Easy

Variables are containers for storing data in computer memory whose values can be changed while the program is running.

Types of Declaration

1. Standard (`var`): Used when you want to declare a variable with a specific data type, or declare it without providing an initial value (zero value).

2. Short Declaration (`:=`): A quick way to create variables. The data type is automatically guessed by Go. Can only be used within functions, not at the package level (global).

Constants

Constants (const) are variables whose values CANNOT be changed once defined. Suitable for fixed values like PI (3.14) or URL configurations.

MAIN.GO
package main
import "fmt"
func main() {
// 1. Standard declaration
var name string = "Raffi"
fmt.Println(name)
// 2. Declaration without type (Type inferred automatically)
var age = 20
fmt.Println(age)
// 3. Short Declaration (Most commonly used)
country := "Indonesia"
fmt.Println(country)
// 4. Constants
const pi = 3.14
fmt.Println(pi)
}