Variables and Types
Go is a statically typed language, meaning variable types are known at compile time. However, its syntax is designed to be concise, often inferring types for you.Variable Declaration
There are three main ways to declare variables in Go.1. var keyword (Explicit Type)
Use this when you want to declare a variable without initializing it immediately, or when you want to be explicit about the type.
2. var keyword (Type Inferred)
If you provide an initial value, you can omit the type.
3. Short Declaration :=
Inside functions, you can use the := operator. This is the most common and idiomatic way to declare and initialize variables in Go.
:= is Preferred: It’s concise and lets the compiler infer types, making code cleaner while maintaining type safety.
Basic Types
Go has a rich set of built-in types.Integers
int,int8,int16,int32,int64uint,uint8,uint16,uint32,uint64,uintptr
int and uint are platform-dependent (32-bit on 32-bit systems, 64-bit on 64-bit systems). In 99% of cases, just use int.
Floats
float32,float64
float64 is the default for floating-point numbers.
Booleans
bool(true or false)
Strings
string(immutable sequence of bytes, UTF-8 encoded)
Complex Numbers
complex64,complex128
Zero Values
Variables declared without an initial value are given their zero value. This is a key safety feature: Go does not have uninitialized variables. Every variable always has a well-defined value.| Type | Zero Value |
|---|---|
int | 0 |
float | 0.0 |
bool | false |
string | "" (empty string) |
| pointers | nil |
| slices | nil |
| maps | nil |
| channels | nil |
Constants
Constants are declared usingconst. They can be character, string, boolean, or numeric values.
:= syntax.
Iota
iota is a special identifier used to create enumerated constants. It resets to 0 whenever const appears and increments by 1 for each line.
Type Conversion
Go requires explicit type conversion. There is no implicit casting (e.g., you cannot assign anint to a float64 variable without casting).
f = i, the compiler will throw an error.