Skip to content

Beginner · Getting started with Go · topic 5 of 46 · 30 min

Constants, iota and type conversions

Explanation

A constant is a value fixed when the program is compiled, declared with const. iota counts 0, 1, 2 inside a const block, which is handy for lists of options. Go never converts types for you: to mix an int and a float64 you write float64(n) yourself, and text-to-number needs the strconv package.

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.

go
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)
}
Constants can be numbers, strings or bools. They cannot be slices, maps or structs.

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.

go
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: 72
The same constant works with both types. A typed variable would not.

iota: 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).

go
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
)
iota restarts at 0 in every new const block. _ throws a value away.
Tip: Start your enum at iota + 1, or keep 0 for an "Unknown" value, so a forgotten field (zero value) is not mistaken for a real status.

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.

go
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) // 15
int(9.99) truncates towards zero. Use math.Round first if you want rounding.

Text 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).

go
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.5
Atoi and ParseFloat return a value and an error. Itoa cannot fail.
Careful: Common mistake: string(65) does NOT give "65". It gives "A", because it treats 65 as a Unicode code point (go vet warns about this). To turn a number into its digits, use strconv.Itoa(65) or fmt.Sprint(65).

Quick reference

You haveYou wantWrite
intfloat64float64(n)
float64int (cut fraction)int(f)
intstring "42"strconv.Itoa(n) or fmt.Sprint(n)
string "42"intn, err := strconv.Atoi(s)
int32int64int64(x)
runestringstring(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

Constants and conversions

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.

go
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")
	}
}
Placed is 1 because the block starts at iota + 1, so OutForDelivery is 3.

Practice (0/4 done)

Task 1 · Question

What are the values of A, B and C? const ( A = iota B C )

Task 2 · Question

What does this print? fmt.Println(int(7.9), int(-7.9))

Task 3 · Question

What does this print? fmt.Println(strconv.Itoa(65) + "!", string(rune(65)) + "!")

Task 4 · Practice

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

Question 1

1.Which of these can be a constant in Go?

Question 2

2.x := 5 (int) and y := 2.5 (float64). What does x * y do?

Question 3

3.What does strconv.Atoi return?

Question 4

4.In a new const block, what is iota on the first line?

Question 5

5.Why does var f float64 = 3 compile without a conversion?

Read more (free)

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.

From Variables, types and constants

What is (int) 7.9?Related

Answer: 7

Conversion to int truncates.

From Type conversion and casting

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.

From Variables, basic types and zero values

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.

From Variables, mutability, shadowing and constants

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

  1. This is the last topic of “Getting started with Go”. The module exam comes next.
  2. Module 1 exam: Getting started with Go · 14 questions · 20 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Control flow and functions. 46 topics left in the course before the final exam.

← Previous: Variables, basic types and zero values