Numbers and Casts
Lesson 5 of 48 in Coddy's Rust for JavaScript Developers course.
Every JavaScript number is a 64-bit floating-point value, even when it holds a count. Division keeps the fraction, and integers are exact only within the safe range up to 2 ** 53: beyond it, 2 ** 53 + 1 evaluates to 2 ** 53. BigInt is a separate type that throws if mixed with number in arithmetic. Rust makes you choose a bounded type such as i32, u32, u64 or f64, and integer division discards the fractional part toward zero, which matches Math.trunc, not Math.floor. A JavaScript product that grows large simply becomes a bigger float. A Rust integer has a fixed width, so widen before arithmetic when the result may exceed the narrower range. A cast with as converts the value; widening u32 to u64 always fits, while a cast to a narrower type silently truncates and is not a range check. The programs divide two integers and then multiply a u32 whose product needs 64 bits. Choose types from the contract.
Complete standalone JavaScript program:
const seconds = 5000000;
console.log(7 / 2);
console.log(Math.trunc(-7 / 2));
console.log(seconds * 1000);
JavaScript output:
3.5
-3
5000000000
Complete standalone Rust program:
fn main() {
let seconds: u32 = 5_000_000;
println!("{}", 7i32 / 2);
println!("{}", -7i32 / 2);
println!("{}", (seconds as u64) * 1000);
}
Rust output:
3
-3
5000000000
Challenge
EasySplit elapsed seconds. Input is one unsigned integer from 0 through 1000000. Required API: pub fn whole_minutes(seconds: u32) -> u32 returns the number of complete minutes; pub fn leftover_seconds(seconds: u32) -> u32 returns the remainder from 0 through 59; pub fn milliseconds(seconds: u32) -> u64 widens the argument and multiplies it by 1000. Output minutes:remainder:milliseconds with no spaces. The APIs also accept any u32, including values beyond the input bound. Implement the public API in duration.rs. The supplied exercise.rs parses valid input and calls that API. Return the specified text without a trailing newline; the locked driver adds one newline. Do not print from the API. All input values satisfy the stated bounds.
Implement the required exported APIs and return the result from exercise::solve(input: &str) -> String without a final newline. Do not print in editable code. The locked driver checks required APIs independently, reads all stdin, and prints the returned text with one final newline.
Your code goes in exercise.rs, duration.rs. main.rs holds the supplied input/output code and cannot be edited.
Try it yourself
#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod duration;
use std::io::{self, Read};
fn main() {
let mut input=String::new();
io::stdin().read_to_string(&mut input).unwrap();
// BEGIN PUBLIC API PROBES
assert_eq!(duration::whole_minutes(183), 3);
assert_eq!(duration::leftover_seconds(183), 3);
assert_eq!(duration::milliseconds(183), 183000u64);
assert_eq!(duration::whole_minutes(0), 0);
assert_eq!(duration::leftover_seconds(0), 0);
assert_eq!(duration::milliseconds(0), 0);
assert_eq!(duration::milliseconds(4000000000), 4000000000000u64);
assert_eq!(duration::whole_minutes(183), 3);
// END PUBLIC API PROBES
println!("{}", exercise::solve(&input));
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Rust for JavaScript Developers
1First Rust Programs
Run Rust ModulesOutput and CommentsModules and VisibilityBindings and TypesNumbers and CastsRecap: Storage Invoice4Ownership and Borrowing
Ownership and MovesShared BorrowsMutable BorrowsLifetimes and ViewsBorrowing Recap3Functions and Sequences
Functions and ReturnsArrays and SlicesVectors and IterationRecap: Record ReadingsPractice on your own: Online Rust compiler