A Bit of Help Getting Started

Overview

Some collected hints to get you started.

Derives

#[derive(Eq, PartialEq, Debug)] (1)
pub struct Point { (2)
    x: i32,
    y: i32,
}
1Derives allow to generate some standard functionality
2Any type can carry a visibility modifier to export them

Useful Derives: Debug

#[derive(Debug)]
struct Point {
    x: i32,
    y: i32,
}

fn main() {
    let p = Point { x: 1, y: 2 };
    println!("{:?}", p); (1)
    println!("{:#?}", p); (2)
}
1Debug makes the Debug formatting string work
2There’s also a more structured version, also enabled through it

Useful Derives: Eq, PartialEq

#[derive(Eq,PartialEq,Debug)] (1) (2)
struct Point {
    x: i32, (3)
    y: i32,
}

fn main() {
    let p1 = Point { x: 1, y: 2 };
    let p2 = Point { x: 1, y: 2 };
    if p1 == p2 { (4)
        println!("The same!");
    }
    assert_eq!(p1, p2); (5)
}
1Eq describes total equality: for every pair of values, equality is defined
2PartialEq is enough for getting ==
3Both can only be derived if all inner fields are both
4Equality in action!
5The assert_eq! compares to values and panics if they don’t match!

Unwrap Results and Option

If you expect something to work or an item to be there, use unwrap:

fn main() {
    let file: File = File::open("Cargo.toml").unwrap();
}

This expects the operation to have worked. You can add structured error handling later.

Strings and their slices

Strings and string slices work much the same.

fn main() {
    let slice: &str = "Hello world!";
    let string: String = String::from(slice);
}

Use Strings

In the beginning, habitually use String.

struct Owned {
    string_data: String
}

fn returns_string() -> String {
    String::from("Hello World")
}

fn hello(who: &str) -> String {
    format!("Hello, {}!", who)
}

Testing

use my_library::my_function; (1)

#[test]
fn my_test() {
    assert_eq!(1, 1);
}

#[test]
#[should_fail]
fn failing_test() {
    assert_eq!(1, 2);
}

Rust and Cargo allows you to easily provide test for your code.

These can be put either directly in the source file or in any file in tests.

1Only needed when putting files in tests.

Test first

fn addition(a: i32, b: i32) -> i32 {
    todo!()
}

#[test]
fn addition_test() {
    assert_eq!(addition(1,2), 3);
}