capypad
0 day streak
go / beginner
Snippet

Type Inference with Short Variable Declaration

Go supports type inference using the := operator. The compiler automatically determines the variable's type based on the assigned value. This makes code cleaner while maintaining static typing - Go is still a statically typed language, the compiler just figures out the type for you. You can declare multiple variables in a single statement.

snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package main
 
import "fmt"
 
func main() {
name := "Alice" // string inferred
age := 28 // int inferred
price := 19.99 // float64 inferred
isStudent := true // bool inferred
 
fmt.Printf("Name: %s, Age: %d\n", name, age)
fmt.Printf("Price: %.2f, Student: %v\n", price, isStudent)
 
a, b := 100, "hello" // multiple variables
fmt.Println(a, b)
}
Breakdown
1
name := "Alice"
The compiler infers this is a string type
2
age := 28
The compiler infers this is an int type
3
price := 19.99
Decimal literals default to float64 type
4
a, b := 100, "hello"
Multiple variables with different types in one statement