0
0
Goprogramming~20 mins

Constants in Go - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
๐ŸŽ–๏ธ
Go Constants Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ“ Predict Output
intermediate
2:00remaining
Output of constant iota usage
What is the output of this Go program?
Go
package main
import "fmt"
const (
  a = iota
  b
  c = 5
  d
  e = iota
)
func main() {
  fmt.Println(a, b, c, d, e)
}
A0 1 5 5 4
B0 1 5 5 5
C0 1 5 6 4
D0 1 5 6 5
Attempts:
2 left
๐Ÿ’ก Hint
Remember that iota increments on each line, but explicit assignments reset it.
โ“ Predict Output
intermediate
2:00remaining
Constant expression evaluation
What will this Go program print?
Go
package main
import "fmt"
const (
  x = 3
  y = x * 2
  z = y + 4
)
func main() {
  fmt.Println(x, y, z)
}
A3 6 10
B3 6 7
C3 5 9
D3 6 12
Attempts:
2 left
๐Ÿ’ก Hint
Constants can be expressions using other constants.
โ“ Predict Output
advanced
2:00remaining
Constant block with mixed types
What is the output of this Go program?
Go
package main
import "fmt"
const (
  a = 1
  b
  c = "hello"
  d
  e = 3.14
  f
)
func main() {
  fmt.Printf("%v %v %v %v %v %v", a, b, c, d, e, f)
}
A1 2 hello hello 3.14 3.15
B1 1 hello hello 3.14 3.14
C1 1 hello hello 3.14 0
D1 1 hello hello 3.14 <nil>
Attempts:
2 left
๐Ÿ’ก Hint
Constants repeat the previous value if no new value is given.
โ“ Predict Output
advanced
2:00remaining
Using iota with bit shifting
What does this Go program print?
Go
package main
import "fmt"
const (
  _ = 1 << (iota * 2)
  A
  B
  C
)
func main() {
  fmt.Println(A, B, C)
}
A2 8 32
B1 4 16
C4 16 64
D0 4 16
Attempts:
2 left
๐Ÿ’ก Hint
iota starts at 0, but the first constant is ignored with underscore.
๐Ÿง  Conceptual
expert
2:00remaining
Why are constants preferred over variables for fixed values?
Which is the best reason to use constants instead of variables for fixed values in Go?
AConstants allow dynamic typing which variables do not.
BConstants use less memory than variables because they are stored on the stack.
CConstants can be changed during program execution for flexibility.
DConstants improve code readability and prevent accidental changes at runtime.
Attempts:
2 left
๐Ÿ’ก Hint
Think about safety and clarity in code.