Variables, Constants, and Data Types
Store values using variables, constants, and common Go data types.
Learning objective: Declare variables and constants using beginner-friendly syntax.
Variables
A variable stores a value that can change while the program runs. Go allows both explicit declaration and short declaration with :=.
Constants
A constant stores a value that should not change. Use const for fixed values such as tax rates, app names, or configuration values.
Common Data Types
Common Go types include int for whole numbers, float64 for decimal numbers, string for text, and bool for true or false values.
Example Code
Create or update your Go file, then run the program using go run main.go.
package main
import "fmt"
func main() {
var name string = "Alex"
age := 20
price := 19.90
const country = "Malaysia"
fmt.Println("Name:", name)
fmt.Println("Age:", age)
fmt.Println("Price:", price)
fmt.Println("Country:", country)
}
Key points to remember
- Use := only inside functions.
- Use var when you want to be more explicit.
- Use const for values that should remain fixed.
Practice Exercises
- Declare a string variable for your name.
- Create an integer variable for your age.
- Create a constant for your country name.
Continue Learning
After this lesson, continue to the next lesson or explore related tutorials on VisualStudioTutor.com.