Variables in Go
Variables are used to store values in a program. Go is a statically typed language, which means each variable has a specific type that cannot be changed during runtime.
Variable Declaration
There are several ways to declare variables in Go:
1. Using var keyword with explicit type
var age intvar name stringvar isValid bool2. Using var keyword with initialization
var age = 25 // type inferred as intvar name = "John" // type inferred as stringvar salary = 5000.0 // type inferred as float643. Short declaration using :=
age := 25 // type inferred as intname := "John" // type inferred as stringsalary := 5000.0 // type inferred as float64Basic Types in Go
Go has several basic types:
-
Numeric Types
- Integers:
int,int8,int16,int32,int64 - Unsigned integers:
uint,uint8,uint16,uint32,uint64 - Floating point:
float32,float64 - Complex numbers:
complex64,complex128
- Integers:
-
String Type
string
-
Boolean Type
bool
Multiple Variable Declarations
You can declare multiple variables in a single line:
var x, y int = 10, 20name, age := "John", 25Zero Values
In Go, variables declared without an explicit initial value are given their zero value:
var ( intValue int // 0 floatValue float64 // 0.0 boolValue bool // false stringValue string // "")Constants
Constants are declared using the const keyword:
const ( Pi = 3.14159 MaxValue = 100 Greeting = "Hello")Type Conversion
Go requires explicit type conversion:
var i int = 42var f float64 = float64(i)var u uint = uint(f)Best Practices
- Use short declaration (
:=) inside functions - Use
vardeclarations for package-level variables - Choose meaningful variable names
- Use constants for values that won’t change
- Group related variables using var blocks
Exercise
Try writing a program that:
- Declares variables of different types
- Performs some basic operations
- Prints the results
Example:
package main
import "fmt"
func main() { // Variable declarations name := "Alice" age := 25 height := 1.68
// Print values fmt.Printf("Name: %s\n", name) fmt.Printf("Age: %d\n", age) fmt.Printf("Height: %.2f meters\n", height)}In the next post, we’ll explore control structures in Go, including if statements, loops, and switches!