Fun Rust Facts

This is just a collection of various notes.

Both Scott and John noticed how cool the rustc --explain <error> feature is.

Array Type Declarations

Array type declarations and initializers are a bit different in Rust than in other languages. Here are some examples

// Array type and initialization examples

fn main() {

    // Let compiler figure out that it's an
    // array of 4 i32 elements
    let implicit = [1, 2, 3, 4]; 
    show_four(implicit, "implicit");

    // Explicitly declare using type ; count syntax
    let explicit: [i32; 4] = [5, 6, 7, 8];
    show_four(explicit, "explicit");
    
    // Explicitly declare and initialize
    // an array with 5 elements, each set to the
    // number 33.
    let five_33s: [i8; 5] = [33; 5];    
    println!("five_33s: {:?}", five_33s);
}

// First parameter is array of exactly 4 values of type i32
fn show_four(array: [i32; 4], name: &str) {
    println!("{}: {:?}", name, array); 
}

Expressions

Expressions do not end in a semi-colon, and they return a value. This can be used for function return values as well as interesting things like setting a value in a conditional expression.


fn add(x: i32, y: i32) -> i32 {
    // Equivalent to "return x + y;"
    x + y
}

fn main() {

    // The add function uses an expression to return a value, see above.
    println!("2 + 2 = {}", add(2,2));

    let addend = 2;
    // Expressions can be return a value from a conditional as well.
    let result = {
        if addend > 3 {
            addend
        } else {
            add(addend, addend)
        }
    };
    println!("The result was {}", result);

}