See Tips for golfing in Rust on CGSE.
Program structure examples
Print all the args:
fn main(){for v in std::env::args().skip(1){print!("{v}
")}}
Print a bunch of numbers:
fn main(){for i in 1..101{if i%9>6{print!("{}
",i*i*i)}}}
Parse input:
// Ordinal Numbers
fn main(){for a in std::env::args(){for n in a.parse::<usize>(){ /* code */ }}}
// Fractions
fn main(){for a in std::env::args(){if let[x,y]=a.split("/").flat_map(str::parse).collect::<Vec<u32>>()[..]{ /* code */ }}}
By using for
or if let
we avoid the need for both .unwrap()
and args().skip(1)
.
Stateful iteration:
fn main(){let mut k=1;for i in 0..10{print!("{k}␊");k*=3}}
fn main(){(0..10).fold(1,|k,_|{print!("{k}␊");k*3});}
Random tips
- Use
@
to assign multiple variables to the same value. For examplelet a@mut b=12
orfor a@mut b in 0..=12 {}
orlet [a,..@b]=[1;99]
. [b,a][i%5/4]
instead ofif i%5==4 then{a}else{b}
(for example)print!
with newline in the format string instead ofprintln!
- However
println!()
is shorter thanprint!("␊")
- However
str.repeat(1)
instead ofstr.to_owned()
format!("literal")
instead ofString::new
- Use byte array literals
b"asdf"
- Option as iterable (for example use
flat_map
instead offilter_map
, orfor s in o
instead ofif let Some(s)=o
) - Format specifiers are really powerful. For example
print!("{:¬^7.3}","abcdefghijkl")
prints¬¬abc¬¬
.- I've found
{:.1}
useful to print a single character from a string at an index:fn main(){let n=3;println!("{}",&"abcde"[n..=n])} fn main(){println!("{}",&"abcde"[3..][..1])} fn main(){println!("{:.1}",&"abcde"[3..])}
- I've found
- Remember to use cool methods on ranges like
if(1..=n).all(|x|condition)
- Don't forget
x.min(y)
andx.max(y)
(works on ints, strings, Options…) .zip(0..)
instead of.enumerate()
- Digit sum:
n.to_string().chars().fold(0,|a,c|a+c as i32-48)
- It's often better to think of Rust golf as functional golf (
.fold
is really darn good). x as i32 as usize
etc can eat a lot of bytes, so try to use one numeric type for everything?- If you need to iterate 10, 100, or a 1000 times but don't care about the iterator variable,
for _ in-1..99
is shorter thanfor _ in 0..100{}
use print as p;
oruse println as p;
is useful if you're using enoughprint!
/println!
statements