Challenge - 5 Problems
Go Type Inference Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ Predict Output
intermediateWhat is the output of this Go code using type inference?
Consider the following Go program. What will it print when run?
Go
package main import "fmt" func main() { x := 10 y := 3.5 z := x + int(y) fmt.Println(z) }
Attempts:
2 left
๐ก Hint
Remember Go requires explicit conversion between int and float64 types.
โ Incorrect
In Go, you cannot add int and float64 directly. The float64 y is converted to int before addition, so 3.5 becomes 3, and 10 + 3 = 13.
โ Predict Output
intermediateWhat is the type of variable 'a' inferred by Go?
Look at this Go code snippet. What is the inferred type of variable 'a'?
Go
package main func main() { a := 'G' }
Attempts:
2 left
๐ก Hint
Single quotes in Go denote a rune literal.
โ Incorrect
In Go, single quotes denote a rune literal, which is an alias for int32. So 'G' is of type rune.
๐ง Debug
advancedWhy does this Go code cause a compilation error?
Examine the code below. Why does it fail to compile?
Go
package main func main() { var x = 5 x = "hello" }
Attempts:
2 left
๐ก Hint
Check the type inferred for x and what value is assigned later.
โ Incorrect
Variable x is inferred as int from the initial value 5. Assigning a string "hello" to it later causes a type mismatch error.
โ Predict Output
advancedWhat is the output of this Go code using type inference with constants?
What will this Go program print?
Go
package main import "fmt" func main() { const pi = 3.14 radius := 5 area := pi * float64(radius) * float64(radius) fmt.Printf("%.2f", area) }
Attempts:
2 left
๐ก Hint
Look at how radius is converted before multiplication.
โ Incorrect
radius is int, converted to float64 for multiplication with pi (a constant float64). The area is 3.14 * 5 * 5 = 78.5, printed with two decimals.
๐ง Conceptual
expertWhich statement about Go's type inference is true?
Select the correct statement about how Go infers types for variables declared with ':='.
Attempts:
2 left
๐ก Hint
Think about static typing and how ':=' works in Go.
โ Incorrect
Go is statically typed. When using ':=', the compiler infers the type from the initial value and the variable's type cannot change later.
