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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package mainimport "fmt"func main() {name := "Alice" // string inferredage := 28 // int inferredprice := 19.99 // float64 inferredisStudent := true // bool inferredfmt.Printf("Name: %s, Age: %d\n", name, age)fmt.Printf("Price: %.2f, Student: %v\n", price, isStudent)a, b := 100, "hello" // multiple variablesfmt.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