Types & Variables
📋 Jump to TakeawaysGo's type system is one of the reasons it catches bugs at compile time instead of 3 AM in production. There are no implicit conversions, no type coercion surprises, and every variable has a zero value, so nothing is ever "undefined."
var Declaration
The var keyword declares a variable with an explicit type. You'll use var when:
- You need a variable outside a function (package level)
- You want the zero value without assigning anything
- You want to specify the type explicitly
var name string = "Go"
var age int = 10
var active bool = trueYou can omit the value and get the zero value, or omit the type and let Go infer it.
var count int // 0 — useful when you just need the zero value
var label = "hi" // type inferred as stringShort Declaration
Inside functions, := is the preferred way. It's shorter and cleaner. But it only works inside functions.
func main() {
name := "Go" // string
age := 10 // int
ratio := 3.14 // float64
active := true // bool
}Use := by default. Reach for var when you have a reason to.
Basic Types
var s string = "hello"
var i int = 42
var i64 int64 = 9223372036854775807
var f float64 = 3.14
var b bool = true
var by byte = 'A' // alias for uint8
var r rune = '⚡' // alias for int32, represents a Unicode code pointZero Values
Uninitialized variables get a zero value. Go never has undefined or null surprises.
var s string // ""
var i int // 0
var f float64 // 0.0
var b bool // false
var p *int // nil
var sl []int // nil
var m map[string]int // nilConstants
Constants are declared with const. They cannot be changed after declaration.
const Pi = 3.14159
const AppName = "ByteLearn"Use iota for sequential constants (enums):
const (
Sunday = iota // 0
Monday // 1
Tuesday // 2
Wednesday // 3
)Type Conversion
Go has no implicit type conversion. You must convert explicitly.
i := 42
f := float64(i) // int → float64
back := int(f) // float64 → int (truncates)
n := 65
ch := string(n) // int → string (Unicode code point, not "65")
import "strconv"
s := strconv.Itoa(65) // "65" — use strconv for number-to-stringType Aliases
Create custom types based on existing ones. This adds type safety, so you can't mix them without conversion.
type Celsius float64
type Fahrenheit float64
var temp Celsius = 100.0
// var f Fahrenheit = temp // compile error: different types
var f Fahrenheit = Fahrenheit(temp) // explicit conversion requiredKey Takeaways
varfor explicit declarations;:=for short declarations inside functions- Basic types:
string,int,float64,bool,byte,rune - Zero values:
0,"",false,nil— no uninitialized surprises constwithiotacreates clean enumerations- Go requires explicit type conversion — no implicit casting
- Custom type aliases add type safety