Variables & Types
Static typing and variable declaration
Introduction
In this lesson, you'll learn about variables & types in Go. Coming from JavaScript, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.
In JavaScript, you're familiar with static typing and variable declaration.
Go has its own approach to static typing and variable declaration, which we'll explore step by step.
The Go Way
Let's see how Go handles this concept. Here's a typical example:
package main
var name string = "Alice"
var age int = 30
var score float64 = 9.5
var active bool = true
const Max = 100
// Short declaration (inside functions)
city := "Istanbul" // type inferred
// Multiple assignment
x, y := 1, 2
a, b := b, a // swap!Comparing to JavaScript
Here's how you might have written similar code in JavaScript:
let name = "Alice";
let age = 30;
let score = 9.5;
let active = true;
const MAX = 100;
// Destructuring
const [first, second] = [1, 2];
const { x, y } = point;You may be used to different syntax or behavior.
Go is statically typed; types cannot change after declaration
You may be used to different syntax or behavior.
Go := is short declaration with inference; used inside functions
You may be used to different syntax or behavior.
Go has separate int and float64 types; JS has just number
You may be used to different syntax or behavior.
Go no destructuring syntax; use multiple assignment x, y := 1, 2
Step-by-Step Breakdown
1. Short Declaration
Go's := declares and initializes with type inference — simpler than JS let/var but types are still fixed.
let city = "Istanbul";city := "Istanbul" // string inferred, fixed2. Numeric Types
Go has separate int and float64 types. Unlike JS's single number type, Go integers and floats are distinct.
let count = 5; let ratio = 0.5;count := 5 // int
ratio := 0.5 // float643. Multiple Assignment
Go supports assigning multiple values at once — useful for swapping and receiving multiple return values.
a, b := 1, 2
a, b = b, a // swap without temp variableCommon Mistakes
When coming from JavaScript, developers often make these mistakes:
- Go is statically typed; types cannot change after declaration
- Go := is short declaration with inference; used inside functions
- Go has separate int and float64 types; JS has just number
Key Takeaways
- Go types fixed at declaration; JS types are dynamic
- Go := for short declaration with inference
- Separate int and float64; JS has only number
- Multiple assignment replaces destructuring