Rust · Chapter 2 of 26
Numbers and text
By the end of this chapter you can pick the right whole-number type for a value, say what happens when a number gets too big for its type, convert between number types knowing what as cuts, round money to the nearest paisa with whole numbers, name fixed values with const, reuse a name with shadowing, count the bytes and the characters of a text, and print numbers and text in neat columns with format! and println!. 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
- Rust
- Free chapter
Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.
Why you need this
Neha pays every farmer every ten days. Ten days of milk come to ₹2,93,19,519.00, which is 2,93,19,51,900 paise. In chapter 1 a whole number with no type said was an i32, and an i32 stops at 2,14,74,83,647: the total does not fit. Written into the program, it does not even build:
error: literal out of range for `i32`
--> range.rs:2:22
|
2 | let total: i32 = 2_931_951_900;
| ^^^^^^^^^^^^^
|
= note: the literal `2_931_951_900` does not fit into the type `i32` whose range is `-2147483648..=2147483647`
= help: consider using the type `u32` instead
...
Chapter 1's amounts also dropped the fraction of a paisa, because whole numbers divide that way. On Tuesday 13 October, 4,436 of the 9,864 accepted cans came to a fraction of half a paisa or more, which dropping throws away: paid that way, the farmers would have lost ₹44.36 in one day, a paisa at a time. Neha's rule is to round to the nearest paisa.
And the slip. The box's printer prints 32 characters a line, and the slips must line up: labels on the left, values on the right, whatever the numbers are. With {} alone a value takes exactly as much room as it needs, so a 12-litre can and a 3-litre can push their lines out of line. And the rupee sign is stranger than it looks: the text "₹29.80" shows 6 characters but Rust says its length is 8.
The lesson
Whole numbers come in sizes
Rust has a whole-number type for every size, in two families. The i types are signed: they hold negative numbers too. The u types are unsigned: zero and up, with twice the room above zero. The number is how many bits the value takes: u8 is one byte, u64 is eight.
println!("u8 {} to {}", u8::MIN, u8::MAX);
println!("i8 {} to {}", i8::MIN, i8::MAX);
println!("u32 up to {}", u32::MAX);
println!("i32 {} to {}", i32::MIN, i32::MAX);
println!("u64 up to {}", u64::MAX);
println!("u128 up to {}", u128::MAX);
println!("usize up to {}", usize::MAX);
u8 0 to 255
i8 -128 to 127
u32 up to 4294967295
i32 -2147483648 to 2147483647
u64 up to 18446744073709551615
u128 up to 340282366920938463463374607431768211455
usize up to 18446744073709551615
usize is as big as the machine's addresses (64 bits here). Rust uses it for lengths, counts and positions: the length of a text is a usize.
Which to pick? Ask what the value can be. Millilitres, fat, members and paise are never negative, so DoodhSetu makes them unsigned: u32 for a can's ml, fat and SNF, u64 for money, which adds up across thousands of cans. An unsigned type also refuses a value that makes no sense:
error[E0600]: cannot apply unary operator `-` to type `u32`
--> neg.rs:2:24
|
2 | let members: u32 = -5;
| ^^ cannot apply unary operator `-`
|
= note: unsigned values cannot be negated
You give a type with a colon after the name, let ml: u32 = 5250;, or as a suffix on the number itself, 5250u32. Long numbers may have underscores anywhere, which Rust ignores: 5_250u32, 2_931_951_900.
Overflow
What happens when a value passes its type's limit? Here a count of cans is a u8, which stops at 255:
fn main() {
let mut cans: u8 = 254;
cans += 1;
println!("cans: {cans}");
cans += 1;
println!("cans: {cans}");
}
$ cargo run -q --bin overflow
cans: 255
thread 'main' (280) panicked at overflow.rs:5:5:
attempt to add with overflow
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
$ cargo run -q --release --bin overflow
cans: 255
cans: 0
A debug build checks every sum, and stops the program with a panic: the program ends at once with a message saying where and why. A release build leaves the checks out for speed, and the number wraps: past 255 a u8 starts again at 0. Neither is what a box should do, which is why you pick a type with room to spare. When the compiler can see an overflow coming from the code alone, it refuses to build at all:
error: this arithmetic operation will overflow
--> sub.rs:4:16
|
4 | let kept = poured - spilled;
| ^^^^^^^^^^^^^^^^ attempt to compute `4880_u32 - 5000_u32`, which would overflow
checked_add and saturating_add
When a sum might not fit, ask the number how it should go. Every integer type has methods for it, called with a dot after the value:
let cans: u8 = 254;
println!("{:?}", cans.checked_add(1));
println!("{:?}", cans.checked_add(2));
println!("{}", cans.saturating_add(2));
println!("{}", cans.wrapping_add(2));
Some(255)
None
255
0
checked_addgivesSome(255)when the sum fits andNonewhen it does not. Read them as "a value" and "nothing": chapter 8 shows how to use them. Print them with{:?}, the debug form.saturating_addstops at the limit: 254 plus 2 is 255.wrapping_addwraps on purpose, in every build.
There are _sub and _mul versions of each.
Converting with as
Chapter 1 used as between whole numbers and decimals. It converts between integer types too, and from a small type to a bigger one it is always safe: litres as u64. The other way, it keeps only what fits:
let members: u32 = 186;
println!("{}", members as u8);
let big: u32 = 300;
println!("{}", big as u8);
let minus: i32 = -1;
println!("{}", minus as u32);
186
44
4294967295
186 fits in a u8. 300 does not: a u8 is the last 8 bits of the number, and 300 is 256 plus 44, so as u8 silently gives 44. And -1 read as unsigned becomes the biggest u32. as never fails and never panics, so use it to make a number bigger, and think twice before making one smaller.
Rounding to the nearest paisa
An f64 has a round method, which goes to the nearest whole number (a half goes away from zero: 2.5 is 3). For a can of 3,120 ml at 3,346 paise a litre:
let ml: u64 = 3120;
let rate: u64 = 3346;
let exact = ml as f64 * rate as f64 / 1000.0;
println!("{exact}");
println!("{}", exact.round());
println!("{}", ml * rate / 1000);
println!("{}", (ml * rate + 500) / 1000);
10439.52
10440
10439
10440
Whole-number division drops the .52 and pays 10,439. Rounding pays 10,440. Neha's rule gets the rounded answer without a decimal at all: add half of what you divide by (500 is half of 1000), then divide. A remainder of 500 or more carries the result up by one; less than 500 does not. Every amount in DoodhSetu's data is made this way, and money never touches an f64.
const: values with names
A constant is a value fixed for the whole program, made with const outside fn main (or inside it). Its type must be written, and by custom its name is in capitals:
const COW_MIN_FAT: u32 = 30;
const PRINTER_WIDTH: usize = 32;
fn main() {
println!("{COW_MIN_FAT} {PRINTER_WIDTH}");
}
30 32
Leave the type out and the compiler asks for it:
error: missing type for `const` item
--> constbad.rs:1:18
|
1 | const COW_MIN_FAT = 30;
| ^ help: provide a type for the constant: `: i32`
A const is not a variable: it can never be mut, and the compiler puts its value straight into every place that uses it. A rate written once as a named constant, rather than as 30 in five places, changes in one place when the chart changes.
Shadowing
let with a name you already have makes a new variable that hides the old one, which is called shadowing. It can even change the type:
let ml = 4880;
let ml = ml + 250;
println!("{ml} ml");
let ml = ml as f64 / 1000.0;
println!("{ml} litres");
5130 ml
5.13 litres
mut is different: it changes the value of one variable, whose type is fixed. Try to put a decimal into an integer variable:
error[E0308]: mismatched types
--> mutbad.rs:3:10
|
2 | let mut ml = 4880;
| ---- expected due to this value
3 | ml = ml as f64 / 1000.0;
| ^^^^^^^^^^^^^^^^^^ expected integer, found `f64`
Shadow when a value becomes another form of itself (millilitres to litres, a number to its text); use mut for a value that keeps changing, like a count.
char, and text as bytes
A char is one character, in single quotes: 'A', '₹'. Every char takes 4 bytes, room for any character in any language. Single quotes hold exactly one; more is an error that suggests double quotes:
error: character literal may only contain one codepoint
--> charbad.rs:2:17
|
2 | let rupee = '₹29';
| ^^^^^
Text in double quotes is different. Rust stores text as UTF-8: each character as 1 to 4 bytes. English letters, digits and the point take 1 byte; the rupee sign takes 3. len counts bytes; chars walks the text one character at a time, and count counts them:
let price = "₹29.80";
println!("{} bytes, {} characters", price.len(), price.chars().count());
let village = "Boriavi";
println!("{} bytes, {} characters", village.len(), village.chars().count());
8 bytes, 6 characters
7 bytes, 7 characters
len is instant, because the text knows its size in bytes. Counting characters has to read every byte, because they are not all the same size.
format! and the format options
format! takes the same text and placeholders as println!, but instead of printing, it gives you the text to keep in a variable. Chapter 5 says what kind of value that is (a String); for now, it is text you can print later.
let minutes = 365;
println!("{}:{}", minutes / 60, minutes % 60);
println!("{:02}:{:02}", minutes / 60, minutes % 60);
let shift = "morning";
let note = format!("{shift} shift opened at {:02}:{:02}", minutes / 60, minutes % 60);
println!("{note}");
6:5
06:05
morning shift opened at 06:05
{:02} prints at least 2 digits, with zeros in front: 5 becomes 05. After the colon in a placeholder come more options:
println!("[{:>8}]", 3346);
println!("[{:<12}]", "Boriavi");
println!("[{:^9}]", "cow");
println!("[{:>8}]", "₹29.80");
println!("[{:>3}]", "Boriavi");
[ 3346]
[Boriavi ]
[ cow ]
[ ₹29.80]
[Boriavi]
- A number is a width: the value takes at least that many characters.
>puts it on the right,<on the left,^in the middle. Numbers go right and text goes left when you say nothing.- The width counts characters, not bytes: "₹29.80" got 2 spaces.
- A value longer than the width is never cut.
println!("[{:08.2}]", 33.46);
println!("[{:-^20}]", " Boriavi ");
println!("{:+} ml, {:+} ml", 250, -120);
println!("box {} is {:x} in hex", 2002, 2002);
println!("{{shift}} is printed as it is");
[00033.46]
[----- Boriavi ------]
+250 ml, -120 ml
box 2002 is 7d2 in hex
{shift} is printed as it is
{:08.2}: width 8, filled with zeros, 2 digits after the point.- A character before the alignment fills the space:
{:-^20}. {:+}always shows the sign;{:x}prints in hexadecimal.{{and}}print a brace itself. A single{shift}with no variable called shift is an error (E0425, cannot find value).
Your turn
Four programs, run each with cargo run --bin and its name. Task 1 prints the price of a litre on both rate charts in columns, with the charts' paise as constants. Task 2 rounds a can's amount to the nearest paisa with whole numbers only and prints it in rupees: the trap is a paise part under
- Task 3 prints a can's slip for the 32-character printer, every line exactly 32 wide. The Check runs all three with other numbers in the lines you keep. Task 4 is an interview question: Lakhan's program says "₹30" has 5 characters; fix it, and be ready for Farhan to ask why the length is 5 and how to count characters.
What you build: 4 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1
table.rs: the rate table for both charts
Neha wants the price of a litre on both rate charts, for milk with the fat and SNF in the lines let fat: u32 = 61; and let snf: u32 = 87; (tenths of a percent). The cow chart pays 32 paise for each tenth of fat and 20 for each tenth of SNF; the buffalo chart pays 40 and 16. Keep those four paise as constants made with const, typed, with upper-case names (the Check looks for at least four const lines). Then print exactly:
Rates at 6.1% fat, 8.7% SNF
Kind Fat SNF Litre
cow 32 20 3692
buffalo 40 16 3832
The kind is left-aligned in 8 characters; Fat, SNF and Litre, and the numbers under them, are each right-aligned in 6. A litre is fat times the fat paise plus snf times the SNF paise. The first line shows 61 as 6.1 and 87 as 8.7.
Keep the two let lines as they are: the Check also runs table.rs with fat 72 and snf 90, and then it must print Rates at 7.2% fat, 9.0% SNF, a cow litre of 4104 and a buffalo litre of 4320.
- Task 2
amount.rs: an amount to the nearest paisa, in rupees
A can of 4730 ml was paid at 3868 paise a litre, in the lines let ml: u64 = 4730; and let rate: u64 = 3868;. That is 18295.64 paise exactly, and Neha pays to the nearest paisa: 18296. Work it out with whole numbers only, with Neha's rule (add 500 before dividing by 1000, so a half paisa rounds up), and with no f64 anywhere in the file (the Check looks). Then print exactly:
Amount: 18296 paise
Amount: ₹182.96
The second line is the rupees, a point, and the paise left over, always as two digits: 7004 paise is ₹70.04, not ₹70.4.
Keep the two let lines as they are: the Check also runs amount.rs with ml 1500 and rate 3001 (4501.5 exactly: Amount: 4502 paise and Amount: ₹45.02), with ml 2000 and rate 3502 (Amount: 7004 paise and Amount: ₹70.04), and with ml 0 and rate 3868 (Amount: 0 paise and Amount: ₹0.00).
- Task 3
slip.rs: a can's slip for the 32-character printer
The box's printer prints 32 characters a line. Print the slip for the can in the six let lines of the starter (society S014, farmer F10650, ml 3010, fat 55, snf 90, paise 10956), every line exactly 32 characters wide:
================================
DoodhSetu slip
Society S014
Farmer F10650
Litres 3.010
Fat % 5.5
SNF % 9.0
Amount Rs 109.56
================================
The first and last lines are 32 = signs. The title is centred in 32 characters: 9 spaces, DoodhSetu slip, 9 spaces. Each other line is its label left-aligned in 12 characters, then its value right-aligned in 20. Litres are ml with three digits after the point (3010 is 3.010), fat and SNF have one (55 is 5.5, 90 is 9.0), and the amount is rupees with two paise digits (10956 is 109.56).
Keep the six let lines as they are: the Check also runs slip.rs with S067, F12733, ml 5090, fat 50, snf 90, paise 17306 (then 5.090, 5.0, 9.0 and 173.06) and with S120, F14758, ml 12560, fat 41, snf 86, paise 38082 (then 12.560, 4.1, 8.6 and 380.82).
- Task 4 · interview question
Interview: length.rs, the text that is longer than it looks
Lakhan's program reports how long a price label is, so the box knows whether it fits on the printer. For "₹30" it says 5 characters, but anyone can see 3. Fix it so that it prints exactly:
Text: ₹30
Bytes: 5
Characters: 3
Bytes is how many bytes the text takes; Characters is how many characters it has.
Keep the line let text = "₹30"; as it is: the Check also runs length.rs with the text ₹1,24,158.97 (Bytes: 14 and Characters: 12) and with Karamsad (Bytes: 8 and Characters: 8).
Farhan will ask: why does "₹30" have a len of 5 when it shows 3 characters, and how do you count its characters?
What you will learn
- Integer types: u8 to u128, i8 to i128, usize, and when a number should be unsigned.
- Overflow: what a debug build and a release build do when a number passes its type's limit, and checked_add and saturating_add.
- as between integers: what it keeps and what it cuts.
- Rounding: f64's round, and Neha's whole-number rule.
- const and shadowing: fixed values with names, and a name reused.
- char and text: one character, and text as UTF-8 bytes.
- format! and the format options: widths, alignment, zeros, signs.
More in The language
Build "Numbers and text" yourself
DoodhSetu runs the milk collection boxes of 120 village societies around Anand. The old box program crashed on an empty line, and you rebuild it in Rust. 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.