One-liners

Contents

One-liners#

Single-expression idioms the operator pastes into a Rust file.

Read a whole text file.

let text = std::fs::read_to_string("notes.txt")?;

Write a whole file.

std::fs::write("out.bin", &payload)?;

Parse an integer with ?.

let n: i64 = s.parse()?;

Collect an iterator into a Vec.

let v: Vec<_> = xs.iter().map(|x| x * 2).collect();

Filter, map, collect.

let v: Vec<_> = xs.iter().filter(|&&x| x % 2 == 0).map(|x| x * x).collect();

Sum of squares.

let total: i64 = xs.iter().map(|x| x * x).sum();

Top-N by key.

let top: Vec<_> = xs.iter().take(10).collect();

Default value with unwrap_or.

let port = cfg.port.unwrap_or(8080);

Pretty-print JSON with serde_json.

let s = serde_json::to_string_pretty(&obj)?;

Open a TCP connection with a timeout.

let stream = std::net::TcpStream::connect_timeout(&addr, std::time::Duration::from_secs(3))?;

References#

  • Snippets for the snippets catalogue.

  • Types for the underlying types.

  • Errors for ? and Result.