Numbers and Casts
Lesson 5 of 48 in Coddy's Rust for Kotlin Developers course.
Kotlin Int and Long have signed 32-bit and 64-bit ranges, corresponding to Rust i32 and i64. Kotlin also has unsigned types, so choose by range rather than assuming every numeric source value is signed. Numeric conversions use methods such as toDouble; Kotlin as is a runtime type cast, not a numeric widening operation.
Both examples truncate signed integer division toward zero. Converting an operand before division selects floating arithmetic, while converting the already computed integer quotient cannot recover its discarded fraction. Rust as performs supported primitive conversions but is not a losslessness guarantee. Kotlin fixed-width integer arithmetic wraps on overflow; Rust overflow may panic when checks are enabled. Use safe bounds and explicit checked or wrapping operations when the contract requires them, instead of relying on the compilation mode.
Kotlin: complete program
fun main() {
val n = -7
println((n / 2).toString() + ":" + (n.toDouble() / 2))
}
Rust: complete program
fn main() {
let n: i32 = -7;
println!("{}:{}", n / 2, n as f64 / 2.0);
}Convert before division when the fractional part matters, and check range before a potentially lossy conversion.
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 Kotlin 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