While Rust is very, very rarely competitive in code golfing competitions (Java is often shorter), it can still be fun to golf in. What are some tricks for making Rust code shorter?

Please post only one tip in each answer.


22 Answers 22


Use closures instead of functions

A closure:


is shorter than a function:

fn f(n:i32)->i32{n+1}

Closures longer than one statement need braces but are still far shorter than a function.


Converting &str to String

Never do these:

s.to_string()  // 13 bytes
s.to_owned()   // 12 bytes

This is always shorter:

s.repeat(1)    // 11 bytes

If s is a string literal:

format!(s)     // 10 bytes

For example: use format!("") instead of String::new() to save 2 bytes.

If type inference works:

s.into()       // 8 bytes

Avoid .iter().enumerate()

Let's say you have some x that implements the IntoIterator Trait and you need to call a function f that takes the index of an element and a reference to it. The standard way of doing this is


instead you can do


and save yourself not only the unusually long enumerate but also the call to iter!

  • \$\begingroup\$ Now I want to do this in regular Rust code. \$\endgroup\$
    – Joonazan
    Jun 22, 2022 at 21:14
  • \$\begingroup\$ Unfortunately enumerate produces shorter assembly. godbolt.org/z/hnee1GK34 But zip is better in every other way. It doesn't require the index to be usize. \$\endgroup\$
    – Joonazan
    Jun 22, 2022 at 21:22
  • \$\begingroup\$ it appears that they produce the same assembly starting with rust 1.60 \$\endgroup\$ Jan 1 at 8:57

If you need many mutable variables, it can waste a lot of space declaring them and initializing them, since each requires the mut keyword and you can't do anything like a=b=c=0. A solution then is to declare a mutable array

let mut a=[0;5];

You spend 3 extra bytes each time you use them vs. a normal variable:


but it can often still be worth it.

Using tuples for the same trick is often an even better option:

let mut t=(1,4,"this", 0.5, 'c');

This has the advantage of saving a byte on each use vs. the array:


It also lets them be of different types. On the downside, it requires more characters to initialize.


Use @ to define multiple variables to the same value

@ is meant to define an alias for pattern matching (like destructuring an array but also getting the original array at the same time). But it works with plain variables too.

let a=2;let b=2; // 16 bytes
let(a,b)=(2,2);  // 15 bytes
let a@b=2;       // 10 bytes

It works in destructuring too:

let a=1;let b=1;let c=2;let d=2; // 32 bytes
let(a,b,c,d)=(1,1,2,2);          // 23 bytes
let(a@b,c@d)=(1,2);              // 19 bytes
  • 3
    \$\begingroup\$ If they need to be mutable (otherwise, what's the point), both variables need the mut keyword, e.g. let mut a@mut b=1; \$\endgroup\$
    – Jo King
    Sep 24, 2022 at 1:24

When using string formatting for example with print!(), one can use both numbered and unnumbered formatters to save one byte per item to format:

Best shown with an example:

fn main() {
        "{}{}{}. Yes, {0}{}{2}. All you other{1}{2}s are just imitating.",
        "I'm", " Slim", " Shady", " the real",

Which outputs:

I'm Slim Shady. Yes, I'm the real Shady. All you other Slim Shadys are just imitating.

So the unnumbered formatters will get assigned to the items in order, this allows you to skip the index on them. Note that you can only use one unnumbered formatter per item to format, after that it will get used up.


Skipping trailing semicolons

In functions returning (), where the last expression is also of type (), you don't need the trailing ;:

fn main(){print!("Hello, world!")}

Replace all filter_map with flat_map

It works because:

  • filter_map takes a FnMut(Self::Item) -> Option<B>

  • flat_map takes a FnMut(Self::Item) -> impl IntoIterator

  • Option implements IntoIterator, which will return an iterator with one item for Some and empty iterator for None


When working with strings with newlines in them, you save one byte if you use a literal line break in the source code vs having a \n in the string and/or using println.


is 2 bytes less than:

  • 8
    \$\begingroup\$ Save another byte by using print with literal line break instead of println \$\endgroup\$
    – JayXon
    Aug 2, 2020 at 1:44

Do-while loops

Rust does not have a C-style do-while loop:


But blocks are also expressions in Rust, so you can write:


Reading lines

After considering various things, I think that is generally the shortest way to retrieve a line. The line has a newline, it can be removed by trimming (.trim()) or if that cannot be done by slicing.

let y=&mut"".into();std::io::stdin().read_line(y);

For multiple lines, lines iterator can be used, the iterated line doesn't end in newline then. A glob import is needed to import BufRead, needed for lines to be available for StdinLock<'_> type.

use std::io::*;let y=stdin();y.lock().lines()

When using whole number floating point numbers, you can omit the trailing .0 to save one byte.

let a=1.

is 1 byte less than:

let a=1.0
  • 1
    \$\begingroup\$ When using FP numbers that have an integer part of 0, you can omit the leading zero as well; .0, .5 are both valid \$\endgroup\$
    – Starwort
    Jun 6 at 20:33

Use ..=

Replace all ..i+1 with ..=i to save 1 byte, works on both array index a[i..=i] and range (0..=n)

  • 2
    \$\begingroup\$ clippy actually has a warning for this \$\endgroup\$
    – betseg
    Feb 26, 2020 at 5:20
  • 2
    \$\begingroup\$ The reverse is better for numbers \$\endgroup\$
    – SuperPizz
    Sep 30, 2021 at 20:08

Use closure parameter to define variable instead of let


can be replaced by


to save 5 bytes if the type of a and b can be inferred, it usually works when they are integers or are passed to another function directly in X.

This works well on 2 or more variables, but for a single variable, this could still save 2 bytes if it allows you to get rid of the {}.


Declare multiple variables using pattern matching

(Somewhat of an extension of https://codegolf.stackexchange.com/a/99124/97519)

Using multiple let statements:

let a=x;let b=y;
let a=x;let b=y;let c=z;

Using a tuple match saves 1 char for 2 variables and 3 more chars for ever variable after:


Similarly, you can use array patterns for initializing multiple mutable variables to the same value (this works with immutable variables too but is pretty useless):

let[mut a,mut b]=[x;2];
  • 2
    \$\begingroup\$ Why is the immutable version useless? \$\endgroup\$
    – Wheat Wizard
    Jul 31, 2020 at 20:48
  • 9
    \$\begingroup\$ @AdHocGarfHunter why would you want to initialize two immutable variables to the same value? \$\endgroup\$
    – Doorknob
    Jul 31, 2020 at 22:10

Prefer todo! over panic!

todo! is shorter than panic! by 1 byte, so prefer to use it if you need to panic and exit the program. It's also shorter than print! by a byte, so it can shorten your program if you can output to stderr instead of stdout.

todo!("optional message for stderr")

Use the ? operator to unwrap infallible results. ? is used for error propagation in conjunction with the result and option types, and per this meta post returning them with infallible results is a standard output method. For example, the following code summing the value of a string when interpreted in base a and b, with ?:


and without:


As you can see, with ? it is much shorter, and it works with options as well, although often for smaller gains.

  • \$\begingroup\$ The unwrap in this example is inside a map, usually filter_map is used in this case, but for code golf, just use flat_map instead: |n|n.to_string().chars().flat_map(|c|c.to_digit(10)).sum(), see my answer for why flat_map works \$\endgroup\$
    – JayXon
    Dec 17, 2020 at 9:26
  • \$\begingroup\$ @JayXon you're right, I have a better example up now. \$\endgroup\$
    – Aiden4
    Dec 17, 2020 at 16:01

if let can sometimes be shorter than match

Using match:

match a{M(v)=>expr,_=>other}

Using if let costs 2 bytes if there are only 2 branches and 1 is wildcard:

if let M(v)=a{expr}else{other}

More effective when your match needed {} anyways, like if the types don't match. For example:

match a{M(v)=>{expr;}_=>{other;}}


if let M(v)=a{expr;}else{other;}

saves 1 byte.


Loops are sometimes shorter than iterators

Even with the extra curly braces, in some cases it can be shorter to declare a mutable variable and use a loop instead of using Iterator methods.

For example, to do something with every third element of a slice and then return the last index:

|n:&[_]|{let mut i=0;while i<n.len(){println!("{}",n[i]);i+=3}i-3}
  • \$\begingroup\$ Using any(|x|f(x)>()) is generally shorter than using last() though you are correct loops can sometimes be even shorter \$\endgroup\$
    – mousetail
    Aug 1, 2022 at 12:27

(0..).scan can be shorter than std::iter::successors

If you want to make endless sequences that are based on previous state:


This will be shorter by a character:

(0..).scan(a,|x,_|{let y=*x;*x=/*something*/;Some(y)})

If you don't mind dropping the first case, it can be even shorter:


Get the nth element of a String or &str slice

In rust you can't directly index a string or slice. If you want to build a string from indexes of another string you would typically do this:

s.chars().nth(n).unwrap() // char
s.bytes().nth(n).unwrap() // u8

Shorter is this, but it will depend s so won't work if s is generated from a expression:

s.as_bytes()[n]as char // char, supports only single byte characters
s.as_bytes()[n] // u8

However, if you are ok with a &str (like if you want to collect into a String or concatenate with a existing String). This also supports only single byte characters.

&s[n..][..1] // &str
&s[n..=n] // &str, if `n` is a single variable or sufficiently short expression

If your expression is a literal you can use byte string instead to index it directly:

b"hello world"[n] // u8
b"hello world"[n]as char // char
  • 1
    \$\begingroup\$ &s[n..][..1] and &s[n..n+1] have the same "supports only single byte characters" caveat; slicing strings at non-char boundaries leads to a panic. Still a great tip if that holds though! \$\endgroup\$ Aug 1, 2022 at 19:37
  • 1
    \$\begingroup\$ s.as_bytes() does not consume s, s.into_bytes() does. also no space needed between ] and as, and &s[n..=n] saves one \$\endgroup\$
    – JayXon
    Aug 2, 2022 at 21:42

scan and fold on Iterators can be used for stateful iteration

If your closure consists of variable declarations and iterating over something while keeping an internal state, you might be able to save some bytes by using scan or fold instead of a for loop:

|i:&str|{let(mut a,mut b,mut c)=(1,2,0);for x in i.chars(){/*AAA*/;/*BBB*/;c=/*CCC*/}c}

scan is good for handling many mutable variables, at the cost of some operations (such as assignment) requiring dereferencing with * and needing to collect the final value using a method like last:


fold can also be used in a similar manner by passing values in the accumulator:


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.