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 example let a@mut b=12 or for a@mut b in 0..=12 {} or let [a,b@..]=[1;99].
[b,a][i%5/4] instead of if i%5==4{a}else{b} (for example)
print! with newline in the format string instead of println!
- However
println!() is shorter than print!("␊")
str.repeat(1) instead of str.to_owned()
format!("literal") instead of String::new
- Use byte array literals
b"asdf"
- Option as iterable (for example use
flat_map instead of filter_map, or for s in o instead of if 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..])}
- Remember to use cool methods on ranges like
if(1..=n).all(|x|condition)
- Don't forget
x.min(y) and x.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 than for _ in 0..100{}
use print as p; or use println as p; is useful if you're using enough print!/println! statements
- Macros can be invoked with curly braces
{} instead of parentheses (), and sometimes this lets you omit the semicolon afterwards and save a byte: print!{"{a}"}a+=1 is valid code.