Skip to content
Felix S. Klock II edited this page Dec 11, 2013 · 19 revisions

How do I convert X to Y?

Int to string

Use ToStr.

let x: int = 42;
let y: ~str = x.to_str();

String to int

Use FromStr, and its helper function, from_str.

let x: Option<int> = from_str("42");
let y: int = x.unwrap();

Int to string, in non-base-10

Use ToStrRadix.

use std::num::ToStrRadix;

let x: int = 42;
let y: ~str = x.to_str_radix(16);

String to int, in non-base-10

Use FromStrRadix, and its helper function, from_str_radix.

use std::num::from_str_radix;

let x: Option<int> = from_str_radix("deadbeef", 16);
let y: int = x.unwrap();

File operations

How do I read from a file?

Use File::open to create a File struct, which implements the Reader trait.

use std::path::Path;
use std::io::fs::File;

let path : Path   = Path::new("Doc-FAQ-Cheatsheet.md");
let on_error      = || fail!("open of {:?} failed", path);
let reader : File = File::open(&path).unwrap_or_else(on_error);

How do I iterate over the lines in a file?

Make a BufferedReader on an instance of File (or any other implementation of the Reader trait). Then use the lines method it implements from the Buffer trait.

use std::io::buffered::BufferedReader;

let mut reader = BufferedReader::new(reader);
for line in reader.lines() {
    print!("line: {}", line);
}

String operations

How do I search for a substring?

Use the find_str method.

let str = "Hello, this is some random string";
let index: Option<uint> = str.find_str("rand");

Containers

How do I get the length of a vector?

The Container trait provides the len method.

let u: ~[u32] = ~[0, 1, 2];
let v: &[u32] = &[0, 1, 2, 3];
let w: [u32, .. 5] = [0, 1, 2, 3, 4];

println!("u: {}, v: {}, w: {}", u.len(), v.len(), w.len()); // 3, 4, 5

How do I iterate over a vector?

Use the iter method.

let values: ~[int] = ~[1, 2, 3, 4, 5];
for value in values.iter() {  // value: &int
    println!("{}", *value);
}

(See also mut_iter which yields &mut int and move_iter which yields int while consuming the values vector.)

Contributing to this page

For small examples, have full type annotations, as much as is reasonable, to keep it clear what, exactly, everything is doing. Try to link to the API docs, as well.

Similar documents for other programming languages:

All Categories:

Clone this wiki locally