Variable Declaration
Go has several ways to declare variables:
package main
import "fmt"
func main() { // Full declaration with type var name string = "Gopher"
// Type inference var age = 5
// Short variable declaration (only inside functions) language := "Go"
fmt.Println(name, age, language)}Zero Values
In Go, variables declared without an initial value are given their zero value:
| Type | Zero Value |
|---|---|
int, float64 | 0 |
bool | false |
string | "" (empty string) |
| pointers, slices, maps, channels, functions | nil |
var count int // 0var enabled bool // falsevar message string // ""Declaring Multiple Variables
// Same typevar x, y, z int
// Different typesvar ( name string = "Alice" age int = 30 active bool = true)Basic Types
Numeric Types
var i int = 42 // Platform-dependent size (32 or 64 bit)var i8 int8 = 127 // -128 to 127var ui uint = 100 // Unsigned integervar f float64 = 3.14 // 64-bit floating pointvar c complex128 // Complex numberStrings
s := "Hello, 世界" // Go strings are UTF-8 by defaultfmt.Println(len(s)) // 13 (bytes, not characters!)
// Raw string literal (no escape sequences)path := `C:\Users\Gopher`Booleans
var isGo bool = truevar isPython = falseConstants
Constants are declared with const and cannot be changed:
const Pi = 3.14159const Greeting = "Hello, Gophers!"
// Multiple constantsconst ( StatusOK = 200 StatusNotFound = 404)Type Conversion
Go never does implicit type conversion. You must convert explicitly:
var i int = 42var f float64 = float64(i)var u uint = uint(f)The := Short Declaration
// Only works inside functionsname := "Gopher" // stringcount := 10 // intpi := 3.14 // float64isReady := true // boolTry It Yourself
- Declare variables using all three methods
- Create a constant for your favorite number
- Convert an
inttofloat64and print the result - Experiment with different integer types and their boundaries
Next Step
Now that you know types, let’s explore control flow with if, for, and switch.