Go is a statically typed, complied language known for its simplicity and efficiency. One of the first things every Go developer learns is how to declare variables-whether to store a simple number, a string, or more complex data.
1. Short Variable Declaration(:=
)
This is the most concise way to declare variables in Go. It's used within functions and allows Go to infer the variables's type based on the assigned value.
name := "Gopher"
age := 10
⚠️ You cannot use :=
outside of functions.
2. Explicit Declaration with var
The var keyword is the traditional way to declare variables. It's useful when:
- You want to specify the variables's type
- You're declaring a variable outside of a function
var name string = "Gopher"
var age int
age = 25
This form is more verbose, but it's clearer when types matter.
3. Type Inference with var
If you want Go to infer the type but still want to use var
(example for package-level declarations), you can omit the type:
var isReady = true
Go will automatically assign bool
to isReady
based on the true
value.
4. Grouped Variable Declaration
When you need to declare multiple related variables, Go allows you to group them using parentheses:
var (
name string = "Gopher"
age int = 10
score float64
)
This keeps your code tidy, especially in packages or structs.
5. Constants with const
Use const
to declare values that should never change. Go requires constants to be assigned at the time of declaration.
const Pi = 3.14
const Greeting = "Hello, Go!"
6. Zero Values in Go
If a variable is declared without an intial value, Go assigns a zero value based on its type:
var n int // 0
var s string // ""
var n bool // false
This behavior ensures your code doesn't break due ti uninitialized variables.
7. Best Practices
- Use
:=
for local, short-lived variables - Use
var
when declaring variable outside of functions or when explicit typing is necessary. - Group related variables together for readability
- Use
const
for fixed values