Type inference
- Go course
- Beginner
- Lesson 17/90
- 4 min
Learn how Go infers the type from the right side.
Type inference
Go can infer the type of the left side from the right side. Writing x := 5, Go understands x is an int. Writing y := 3.14, it infers y as float64.
Type inference keeps code concise and readable. But sometimes the type is written explicitly; especially when a specific integer type (e.g. int32) is needed.
For strings, s := "hello" is enough; no need for var s string. Inference happens at compile time; it has no runtime cost.
Inference principles
Type inference follows clear rules: integers become int, decimals float64, characters rune, strings string.
With multiple returns, each value's type is inferred separately. For example a, b := 1, "x" gives a int, b string.
Inference works only at compile time; the type does not change at runtime. Go is statically typed; once set, the type stays.
Practice Inferred types
Declare a := 5, b := 2.5, c := 'x', d := "go" and print the types Go inferred with fmt.Printf("%T %T %T %T\n", a, b, c, d).
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
func main() {
a := 5
b := 2.5
c := 'x'
d := "go"
fmt.Printf("%T %T %T %T\n", a, b, c, d)
}Expected output
int float64 int32 string
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the type of x in x := 3.14?
- float64 Correct answer
- int
- float32
- decimal
Explanation: 3.14 is inferred as float64.
2 Inference example
If x := 5 then x's type is ____.
If x := 5 then x's type is int.
Explanation: Integer literals become int.
3 Match the inferred types
| Term | Meaning |
|---|---|
5 |
int |
3.14 |
float64 |
'a' |
rune |
"x" |
string |