Rust
Online Rust Compiler
Programs are compiled with rustc 1.99 using edition 2024 and run as a native binary, with the standard library only. When your program calls io::stdin().read_line(), it waits for you to type in the terminal.
Try it aboveHow Rust runs here
- Versions
- Rust 1.99
- Build
rustc --edition 2024 -o a.out main.rs- Run
./a.out- Limits per run
- 512 MB memory, 15 s of CPU time on half a core, 2 MB of output
- Time
- Up to 10 minutes a run (30 on a paid plan); waits 2 minutes for input (5 on a paid plan)
- Sandbox
- Each run gets its own Linux sandbox with no network access. Text files your program writes next to your code open as new tabs.
- Good to know
- Standard library only: no Cargo or crates.
A Rust program that reads and ranks input
This main.rs reads a class list line by line, sorts it by score and then by name, and prints a ranking with aligned columns:
use std::io::{self, Write}; fn ask(question: &str) -> String { print!("{question}"); io::stdout().flush().unwrap(); // print! has no newline, so flush it before reading let mut line = String::new(); io::stdin().read_line(&mut line).unwrap(); line.trim().to_string() } fn main() { let n: usize = ask("How many students? ").parse().expect("type a whole number"); let mut scores: Vec<(String, u32)> = Vec::new(); for i in 1..=n { let line = ask(&format!("Student {i} (name score): ")); let mut parts = line.split_whitespace(); let name = parts.next().unwrap_or("?").to_string(); let score: u32 = parts.next().and_then(|s| s.parse().ok()).unwrap_or(0); scores.push((name, score)); } scores.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0))); for (rank, (name, score)) in scores.iter().enumerate() { println!("{}. {name:<6} {score:>3}", rank + 1); } let total: u32 = scores.iter().map(|(_, s)| s).sum(); println!("Average: {:.1}", total as f64 / n as f64); }
Four students typed in; maya and zoe tie on 91 and are ordered by name:
$ rustc --edition 2024 -o a.out main.rs $ ./a.out How many students? 4 Student 1 (name score): maya 91 Student 2 (name score): leo 78 Student 3 (name score): zoe 91 Student 4 (name score): sam 84 1. maya 91 2. zoe 91 3. sam 84 4. leo 78 Average: 86.0
Reading stdin in Rust
The usual way is read_line into a String, then trim() and parse(), as in ask() above. To read many lines, lock stdin once and iterate over lines(). For large output, write through a BufWriter:
use std::io::{self, BufRead, BufWriter, Write}; fn main() { let stdin = io::stdin(); let mut out = BufWriter::new(io::stdout().lock()); for line in stdin.lock().lines() { let line = line.unwrap(); if line.trim().is_empty() { break; // an empty line ends the input } let n: i64 = line.trim().parse().unwrap(); writeln!(out, "{}", n * n).unwrap(); } }
Four things trip people up here:
- read_line keeps the line break, so "42\n".parse::<i32>() fails. Call .trim() before parse().
- read_line appends to the String you pass. Reusing one buffer in a loop without line.clear() gives you "3\n4\n" on the second pass.
- print! doesn’t flush, because Rust’s stdout is line-buffered. A prompt without a newline only shows after io::stdout().flush(). The same goes for a BufWriter, which holds everything until it’s flushed or dropped.
- read_to_string() and lines() run until the end of input, and the terminal never sends one: there’s no Ctrl+D here. Stop on a count you read first, or on an empty line as above.
More than one file: mod
rustc compiles main.rs and follows each mod declaration to the file of the same name, so add util.rs with the + next to the tabs and declare it:
// util.rs pub fn gcd(a: u64, b: u64) -> u64 { if b == 0 { a } else { gcd(b, a % b) } } // main.rs mod util; fn main() { println!("{}", util::gcd(84, 36)); // 12 }
Mark what main.rs uses as pub. A mod line without its file stops the build with error[E0583]: file not found for module `util`. Other .rs files that no mod line names are not compiled.
What isn’t available here
- Cargo and crates. There’s no Cargo.toml and no network, so rand, regex, serde, itertools and tokio are out. The standard library is all there: collections, iterators, String, threads, channels, std::fs inside the sandbox.
- Random numbers without rand. Seed a small generator yourself, for example from std::time::SystemTime::now(), or hard-code a seed so runs repeat.
- Release builds. The build command has no -O, so the binary is a debug build: overflow checks are on and tight loops run slower than cargo run --release would.
- Nightly features. Rust 1.99 is stable, so #![feature(...)] stops the build with error[E0554].
- Windows or GUI crates, and anything that opens a window. Output is text in the terminal.
Errors you’ll see
- “error[E0382]: borrow of moved value: `names`” You used a value after moving it into another variable or function. Borrow with &names, or call .clone() if you need two copies.
- “error[E0502]: cannot borrow `v` as mutable because it is also borrowed as immutable” A reference into v is still alive while you push to it. Finish using the reference first, or copy the value out.
- “error[E0432]: unresolved import `rand`” There are no crates here. Use the standard library.
- “called `Result::unwrap()` on an `Err` value: ParseIntError { kind: InvalidDigit }” parse() got text that isn’t a number, very often the newline that read_line keeps. Trim first.
- “index out of bounds: the len is 3 but the index is 5” A slice or Vec index past the end. Use .get(i), which returns an Option, when the index may be out of range.
- “attempt to subtract with overflow” Debug builds check integer overflow, so 0u32 - 1 panics. Use checked_sub(), saturating_sub() or a signed type.
When a borrow checker error points at one line but the cause is another, Fix with AI under the failed run explains which value is borrowed where and proposes a change as a diff.
Edition 2024 and debug builds in practice
- gen is a reserved keyword in edition 2024, so let gen = 1; no longer compiles. Rename the variable.
- std::env::set_var and remove_var are unsafe functions in edition 2024 and need an unsafe block (error[E0133] otherwise).
- Format strings capture variables by name: println!("{name:<6} {score:>3}") pads and aligns without extra arguments.
- For contest problems, read with stdin.lock().lines() and print through a BufWriter. Debug builds keep overflow checks, which is useful for catching an i32 that should be an i64.
- Panics print the message and the line, such as main.rs:4:31. The program’s exit code is 101.
Questions
Which Rust version and edition does it use?
Rust 1.99 (rustc), with --edition 2024. The binary is a debug build, since no -O is passed.
Can I use crates like rand or regex?
No. Programs are compiled with rustc directly, without Cargo, and there’s no network to download crates. Only the standard library is there.
Why doesn’t my prompt show before the input?
print! without a newline stays in stdout’s buffer. Call io::stdout().flush() (with use std::io::Write) before read_line.
Why does parse() fail on a number I typed?
read_line keeps the trailing newline. Use line.trim().parse::<i32>() instead of line.parse().
Can I split my program into several files?
Yes. Add util.rs, write mod util; in main.rs and mark its items pub. rustc follows mod lines to the matching files.