19
\$\begingroup\$

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.

\$\endgroup\$
7
\$\begingroup\$

Use closures instead of functions

A closure:

|n|n+1

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.

\$\endgroup\$
4
\$\begingroup\$

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

x.iter().enumerate().map(f)

instead you can do

(0..).zip(x).map(f)

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

\$\endgroup\$
4
\$\begingroup\$

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:

a[0]+=1;

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:

t.0=2

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

\$\endgroup\$
0
\$\begingroup\$

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()
\$\endgroup\$
0
\$\begingroup\$

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!")}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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