Go · Chapter 2 of 26
Types, strings and fmt
By the end of this chapter you can choose the right number type and say what happens when one overflows, round money to the nearest paisa, name fixed values with const and iota, tell a string's bytes from its characters, and print any value exactly the way a report needs it with fmt's verbs and widths. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.
- Part: The language
- 4 tasks
- Go
- Free chapter
Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.
Why you need this
Pooja checks BijliGo's bills every morning. Wednesday's 3,600 sessions came to ₹8,31,588, and every one of them was worked out from watt-hours and a tariff: a session of 9,217 Wh on a DC60 charger at 2,400 paise a kWh costs exactly 22,120.8 paise. Chapter 1 divided whole numbers, and Go threw the .8 away: the bill said 22,120. Across a day of sessions, a paisa here and a paisa there adds up, and Pooja's rule is plain: round to the nearest paisa, never cut.
Tenzin has his own list. The tariff report he pastes into the team chat has columns that wander, because each line was printed with Println. The firmware team wants a charger's states as numbers, not words. And the little screen on every charger fits 9 characters, while his program says "₹24 a kWh" is 11 long and refuses to show it.
All four are about types: which number type holds what, what a string really is, and how fmt turns any of them into text. Chapter 1 met int, float64, string and bool; this chapter looks inside them.
The lesson
Whole numbers come in sizes
int is the whole number type you use almost everywhere. Go also has types of a fixed size: int8, int16, int32 and int64 (8 to 64 bits, with a sign), and uint8 to uint64 and uint (no sign, so never below zero). On the lab's machine, as on every 64-bit machine, int is 64 bits: strconv.IntSize says 64.
Each size has a largest value, in the math package:
fmt.Println(math.MaxInt8, math.MaxInt32, math.MaxInt)
127 2147483647 9223372036854775807
What happens past the largest? The compiler stops you when it can see it:
$ go run const8.go
# command-line-arguments
./const8.go:6:19: cannot use 128 (untyped int constant) as int8 value in variable declaration (overflows)
When the value is only known as the program runs, Go does not stop: the number wraps around, like an odometer, with no error and no warning. BijliGo took 83,158,800 paise on Wednesday. Here is a year of that in an int32, and in an int64:
var day int32 = 83158800 // paise BijliGo took on 14 October
year := day * 365
fmt.Println("a year in int32:", year)
var day64 int64 = 83158800
fmt.Println("a year in int64:", day64*365)
a year in int32: 288190928
a year in int64: 30352962000
The int32 answer says ₹28.8 lakh instead of ₹30.4 crore, and looks perfectly normal. A uint wraps the other way too: a uint8 of 255 plus one is 0, and a uint of 0 minus one is 18446744073709551615. That is why BijliGo keeps money in a plain int: at 64 bits it holds more paise than BijliGo will ever take.
Rounding money
Dividing ints drops the remainder, which for money means always rounding down. Here is the 9,217 Wh session at 2,400 paise, three ways:
wh := 9217
tariff := 2400
exact := float64(wh*tariff) / 1000
fmt.Println("exact:", exact)
fmt.Println("cut off:", wh*tariff/1000)
fmt.Println("math.Round:", int(math.Round(exact)))
fmt.Println("Pooja's rule:", (wh*tariff+500)/1000)
exact: 22120.8
cut off: 22120
math.Round: 22121
Pooja's rule: 22121
math.Round(x)rounds a float64 to the nearest whole number, with a half going away from zero (math.Round(2.5)is 3), and gives back a float64.int(...)then makes it an int.- Pooja's rule stays in whole numbers the whole way: adding 500 (half of 1000) before dividing by 1000 turns "cut off" into "nearest". No float64 ever touches the money.
int(2.9)is 2: converting a float64 to an int cuts, it never rounds.
Constants and iota
A value that must never change gets const instead of var:
const peakStart = 18
const tariffDC60 int = 2400
const kwhInWh = 1000
Change one and the compiler refuses: cannot assign to peakStart (neither addressable nor a map index expression).
peakStart and kwhInWh are untyped constants: they are exact numbers that take whatever type the code around them needs. With var kw float64 = 7.4, kw * kwhInWh is a float64 and prints 7400. tariffDC60 is a typed constant, an int, so it follows the int rules: kwh * tariffDC60 with a float64 kwh fails with mismatched types float64 and int, exactly as a variable would.
For a set of related values, a const block and iota number them for you. iota is 0 on the first line of the block and one more on each line after, and a line with only a name repeats the line above it:
const (
Car = iota
Auto
Scooter
)
func main() {
fmt.Println(Car, Auto, Scooter)
}
0 1 2
The firmware sends those numbers, the code reads names, and adding a kind in the middle renumbers the rest without a typo.
A string is bytes
A Go string is a row of bytes, the text written in UTF-8. Letters, digits and spaces take one byte each; other characters take two, three or four. len counts bytes, and utf8.RuneCountInString from the unicode/utf8 package counts characters:
city := "Bengaluru"
kannada := "ಬೆಂಗಳೂರು"
fmt.Println(len(city), utf8.RuneCountInString(city))
fmt.Println(len(kannada), utf8.RuneCountInString(kannada))
fmt.Println(city[0], kannada[0])
fmt.Printf("%c %T\n", city[0], city[0])
9 9
24 8
66 224
B uint8
- The city's name in Kannada is 8 characters and 24 bytes: each Kannada character takes three.
city[0]is not "B": it is the byte 66 (auint8;byteis another name for it).%cprints a number as the character it stands for.- A character is a rune, Go's name for one Unicode code point (an
int32).'₹'in single quotes is a rune, 8377, andstring(r)turns a rune back into text.
Numbers as text: strconv
+ joins strings, but a string and an int cannot meet:
$ go run plus.go
# command-line-arguments
./plus.go:7:14: invalid operation: "Chargers: " + chargers (mismatched types untyped string and int)
The strconv package converts: strconv.Itoa(8) is the string "8".
chargers := 8
fmt.Println("Chargers: " + strconv.Itoa(chargers))
Chargers: 8
Beware string(8): that is the character with code 8, an invisible control character, not "8". The program compiles and prints nothing useful, and go vet says so:
$ go vet itoa.go
itoa.go:11:29: conversion from int to string yields a string of one rune, not a string of digits
Every verb you need
Printf's verbs from chapter 1 take a width: a number after the % pads the value with spaces to that many characters. A - pads on the right instead, a 0 pads a number with zeros, and a width and a precision go together as %8.2f.
fmt.Printf("[%5d] [%-5d] [%05d]\n", 240, 240, 240)
fmt.Printf("[%-18s] [%18s]\n", "Koramangala Mall", "Indiranagar")
fmt.Printf("[%8.2f] [%08.2f]\n", 11.7, 11.7)
fmt.Printf("%q %v\n", "C1002", "C1002")
fmt.Printf("%T %T %T %T\n", 240, 11.7, "C1002", true)
fmt.Printf("%x %X %b\n", 255, 255, 5)
fmt.Printf("Uptime: 96%%\n")
[ 240] [240 ] [00240]
[Koramangala Mall ] [ Indiranagar]
[ 11.70] [00011.70]
"C1002" C1002
int float64 string bool
ff FF 101
Uptime: 96%
- %5d right-aligns in 5 characters, %-5d left-aligns, %05d fills with zeros: the way to make columns line up.
- %q prints a string in quotes, so spaces at the ends show up.
- %T prints a value's type, handy when you are not sure what
:=made. - %x is hexadecimal, %b binary, and %% is a percent sign.
- fmt.Sprintf fills a pattern like Printf but gives the text back as a string instead of printing it:
card := fmt.Sprintf("%-18s|%3d|", station, chargers)
fmt.Printf("%q\n", card)
"Koramangala Mall | 8|"
A wrong verb is caught too: go vet (and so the Check) refuses a %d given a string.
Your turn
Four tasks, one file each. Task 1 prints the tariff table with Printf widths from eight variables; the Check changes two of them, so the columns must come from the widths, not from spaces you typed. Task 2 works out a bill, rounded to the nearest paisa, and prints it as rupees and paise: the trap is ₹101.05 printed as ₹101.5. Task 3 numbers a charger's states with iota. Task 4 is an interview question: Tenzin's program says "₹24 a kWh" is too long for the screen, and Joseph will ask why len("₹24") is 5 and how to count characters. Run each with go run file.go.
What you build: 4 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1
tariffs.go: a tariff table whose columns line up
Pooja wants BijliGo's four tariffs as a table whose columns line up. Keep the eight variable lines of the starter as they are (ac7KW := 7.4, ac7Paise := 1400, dc30KW := 30.0, dc30Paise := 2000, dc60KW := 60.0, dc60Paise := 2400, lev3KW := 3.3, lev3Paise := 900) and print exactly these five lines:
Kind Power Paise
AC7 7.4 kW 1400
DC30 30.0 kW 2000
DC60 60.0 kW 2400
LEV3 3.3 kW 900
After the first line, each line is the kind, left-aligned in 6 characters; the power with one digit after the point, right-aligned in 5 characters, then a space and kW; then the paise, right-aligned in 9 characters. Print them with Printf widths from the variables: the Check also runs tariffs.go with dc60KW := 150.0 and lev3Paise := 12500, and then those two lines must be DC60 150.0 kW 2400 and LEV3 3.3 kW 12500. As given, the file does not compile, because Go refuses variables that are never used.
- Task 2
bill.go: a bill in rupees and paise, rounded
A session used 18437 watt-hours, in the variable wh, at 2400 paise a kWh, in the variable tariff. Keep the lines wh := 18437 and tariff := 2400 exactly as they are, and print exactly:
Exact: 44248.8 paise
Cost: 44249 paise
Bill: ₹442.49
Exact is wh times tariff divided by 1000 as a decimal number, printed with one digit after the point. Cost is that rounded to the nearest whole paisa, with a half rounding up, as an int. The bill is the cost's whole rupees, a point, and the paise left over, always as two digits.
The Check also runs bill.go with wh := 11228 and tariff := 900 (then Exact: 10105.2 paise, Cost: 10105 paise, Bill: ₹101.05) and with wh := 5 and tariff := 900 (then Exact: 4.5 paise, Cost: 5 paise, Bill: ₹0.05).
- Task 3
states.go: a charger's states as iota constants
A charger is in one of four states. Declare them as constants in one const block, numbered with iota: Available, Charging, Offline and Faulted, in that order, and write the first one exactly as Available = iota. Then print each state's number from its constant, a space, and its name in small letters:
0 available
1 charging
2 offline
3 faulted
The numbers must come from the constants: the Check also runs states.go with the first line changed to Available = iota + 1, and then it must print 1 available, 2 charging, 3 offline and 4 faulted.
- Task 4 · interview question
Interview: rupee.go, the price that was too long
A charger's little screen fits 9 characters, and Tenzin's program says the price "₹24 a kWh" is 11 long. Fix it so that it prints exactly:
Price: ₹24 a kWh
Bytes: 11
Characters: 9
Bytes is the length of the string in bytes. Characters is how many characters a person sees. Keep the line price := "₹24 a kWh" exactly as it is: the Check also runs rupee.go with price := "₹9 a kWh, ₹0 to park", and then it must print Bytes: 24 and Characters: 20.
Joseph will ask: why is len("₹24") 5, and how do you count the characters in a string?
What you will learn
- Whole number types: int8 to int64, uint, and what overflow does.
- Rounding: math.Round, and Pooja's integer rule for paise.
- const and iota: names for values that never change, numbered for you.
- Strings are bytes: len, indexing, runes, and unicode/utf8.
- strconv.Itoa: a number as text.
- fmt's verbs and widths: %5d, %-12s, %08.2f, %q, %T, %x, %% and Sprintf.
More in The language
Build "Types, strings and fmt" yourself
BijliGo, a Bengaluru EV charging network, drops chargers at the evening peak. You rewrite its backend in Go. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.
Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.