Beginner · Getting started with Go · topic 5 of 46 · 30 min
Constants, iota and type conversions
Explanation
Constants
A constant is a name for a value that can never change while the program runs, such as the GST rate or the number of days in a week. You declare it with const. The compiler knows the value, so mistakes like changing it are caught at compile time.
const GSTPercent = 18
const AppName = "Daily Bills"
const (
MaxItems = 50
FreeDelivery = 199
)
func main() {
// GSTPercent = 12 // compile error: cannot assign to GSTPercent
fmt.Println(AppName, GSTPercent, MaxItems)
}Untyped constants: flexible numbers
A constant like 18 has no fixed type until you use it. Go calls this an untyped constant. It can be used as an int in one place and a float64 in another, as long as the value fits. This is why var f float64 = 3 works without a conversion.
const Rate = 18
var price float64 = 250.0
var qty int = 4
fmt.Println(price * Rate / 100) // Rate acts as float64: 45
fmt.Println(qty * Rate) // Rate acts as int: 72iota: automatic numbering
Inside a const block, iota is 0 on the first line and goes up by 1 on each next line. If you leave a line empty after the first, Go repeats the previous expression. This gives you a neat list of related values, often called an enum (enumeration).
type OrderStatus int
const (
Placed OrderStatus = iota // 0
Preparing // 1
OutForDelivery // 2
Delivered // 3
)
const (
_ = iota // skip 0
KB = 1 << (10 * iota) // 1 << 10 = 1024
MB // 1 << 20 = 1048576
)No automatic conversions
Many languages quietly convert an int to a float when you mix them. Go refuses. A conversion is written as the type name with brackets: float64(x), int(y), int64(z). This makes every possible loss of precision visible in the code.
marks := 452
maxMarks := 500
// percent := marks * 100 / maxMarks * 1.0 // still int maths, gives 90
percent := float64(marks) * 100 / float64(maxMarks)
fmt.Println(percent) // 90.4
f := 9.99
fmt.Println(int(f)) // 9 (the fraction is cut off, not rounded)
var small int32 = 5
var big int64 = 10
// fmt.Println(small + big) // compile error: mismatched types int32 and int64
fmt.Println(int64(small) + big) // 15Text and numbers: strconv
Converting between text and numbers can fail ("abc" is not a number), so it is done by functions in the strconv package that also return an error. You will learn errors properly in module 4; for now, check that err is nil (no error).
import "strconv"
n, err := strconv.Atoi("42") // "ASCII to integer"
if err != nil {
fmt.Println("not a number:", err)
}
fmt.Println(n + 1) // 43
s := strconv.Itoa(452) // "452"
fmt.Println(s + " marks") // 452 marks
f, _ := strconv.ParseFloat("7.25", 64)
fmt.Println(f * 2) // 14.5Quick reference
| You have | You want | Write |
|---|---|---|
| int | float64 | float64(n) |
| float64 | int (cut fraction) | int(f) |
| int | string "42" | strconv.Itoa(n) or fmt.Sprint(n) |
| string "42" | int | n, err := strconv.Atoi(s) |
| int32 | int64 | int64(x) |
| rune | string | string(r) |
Need help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
Constants, iota and type conversions · 1/7
Some values never change, like the GST rate. We store them as constants.
Prefer a video by a teacher? Find free videos on “golang constants iota type conversion strconv tutorial” on YouTube ↗
In real life: Swiggy-style order status
A food delivery app tracks each order through fixed stages. Using a named type with iota constants means the code says order.Status == OutForDelivery instead of a mystery number like 2, and the compiler stops anyone from passing a random string as a status.
package main
import "fmt"
type OrderStatus int
const (
Placed OrderStatus = iota + 1
Preparing
OutForDelivery
Delivered
)
func main() {
status := OutForDelivery
fmt.Println("status code:", status) // 3
if status == OutForDelivery {
fmt.Println("Your order is on the way")
}
}Practice (0/4 done)
What are the values of A, B and C? const ( A = iota B C )
What does this print? fmt.Println(int(7.9), int(-7.9))
What does this print? fmt.Println(strconv.Itoa(65) + "!", string(rune(65)) + "!")
Write a program with a constant GST percentage of 18. Read a price from a string "250" with strconv.Atoi, handle the error, and print the price with GST as a float64 with 2 decimals.
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Your first program and Go modulesGetting started with Go · same module
- Installing Go and the go commandGetting started with Go · same module
- Variables, types and constantsC++ Programming (modern C++ and DSA) · First steps: compiling, output, variables and input
- Type conversion and castingC Programming (from zero to systems) · Operators and control flow
- Variables, mutability, shadowing and constantsRust Programming · Getting started with Rust
- Your first Dart program, variables and typesFlutter and Dart · Dart basics
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
Which of these can be a constant in Go?
Answer: A string
Constants can be numbers, strings, runes or bools only.
x := 5 (int) and y := 2.5 (float64). What does x * y do?
Answer: Compile error: mismatched types int and float64
Go does not mix types silently. Write float64(x) * y.
What does strconv.Atoi return?
Answer: An int and an error
Atoi can fail on text like "abc", so it returns (int, error).
In a new const block, what is iota on the first line?
Answer: 0
iota resets to 0 at the start of every const block.
Why does var f float64 = 3 compile without a conversion?
Answer: 3 is an untyped constant that can become float64
Untyped constants take on the type they are used as, as long as the value fits.
What is in an int variable declared inside main with int n; and no value?Related
Answer: Garbage: reading it is undefined behaviour
Local variables are not set to zero automatically. Always initialise them.
What is (int) 7.9?Related
Why store money as int64 paise instead of float64 rupees?Related
Answer: Floating point cannot store values like 0.1 exactly, so sums drift
Binary floating point gives tiny rounding errors; whole paise in an integer are exact.
Which constant is written correctly?Related
Answer: const RATE: u32 = 18;
A const needs a type and a value; the name is UPPER_CASE by convention.
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- This is the last topic of “Getting started with Go”. The module exam comes next.
- Module 1 exam: Getting started with Go · 14 questions · 20 min, without help. 5 topics of this module still to finish first.
- Then the next module, Control flow and functions. 46 topics left in the course before the final exam.