beginner getting started

Variables, Types, and Constants in Go

Master Go's basic data types, variable declarations, zero values, and constants. Learn about int, float64, string, bool, and shorthand syntax.

variables types constants

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:

TypeZero Value
int, float640
boolfalse
string"" (empty string)
pointers, slices, maps, channels, functionsnil
var count int // 0
var enabled bool // false
var message string // ""

Declaring Multiple Variables

// Same type
var x, y, z int
// Different types
var (
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 127
var ui uint = 100 // Unsigned integer
var f float64 = 3.14 // 64-bit floating point
var c complex128 // Complex number

Strings

s := "Hello, 世界" // Go strings are UTF-8 by default
fmt.Println(len(s)) // 13 (bytes, not characters!)
// Raw string literal (no escape sequences)
path := `C:\Users\Gopher`

Booleans

var isGo bool = true
var isPython = false

Constants

Constants are declared with const and cannot be changed:

const Pi = 3.14159
const Greeting = "Hello, Gophers!"
// Multiple constants
const (
StatusOK = 200
StatusNotFound = 404
)

Type Conversion

Go never does implicit type conversion. You must convert explicitly:

var i int = 42
var f float64 = float64(i)
var u uint = uint(f)

The := Short Declaration

// Only works inside functions
name := "Gopher" // string
count := 10 // int
pi := 3.14 // float64
isReady := true // bool

Try It Yourself

  1. Declare variables using all three methods
  2. Create a constant for your favorite number
  3. Convert an int to float64 and print the result
  4. 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.