User Tools

Site Tools


rust

This is an old revision of the document!


Rust

Variables

fn main() {
    let x = 5; // Immutable i32 (default)
 
    let mut y = 5.0; // Mutable f32 (default)
    y += 1;
 
    let y = 6; // Shadowing is fine
 
    // Constants need explicit type
    const THREE_HOURS_IN_SECONDS: u32 = 60 * 60 * 3;
 
    let f: bool = false; // Boolean
    let c: char = 'z'; // Character
    let tup: (i32, f64, u8) = (500, 6.4, 1); // Tuple
    let a: [i32; 5] = [1, 2, 3, 4, 5]; // Array
}

Control flow

    if number < 5 {
        println!("condition was true");
    } else {
        println!("condition was false");
    }

Struct methods

Functions in a struct that have self as parameter is called method and it is an associated function.

Associated functions that don't have self as parameters can be used as for example constructors. But they are not called methods.

struct Rectangle {
    width: u32,
    height: u32,
}
 
impl Rectangle {
    fn area(&self) -> u32 {
        self.width * self.height
    }
 
    fn can_hold(&self, other: &Rectangle) -> bool {
        self.width > other.width && self.height > other.height
    }
 
    fn square(size: u32) -> Self {
        Self {
            width: size,
            height: size,
        }
    }
}
 
fn main() {
    let a : Rectangle::square(5);
    let b : Rectangle {
            width: 1,
            height: 2,
        }
 
    println!("Can a fit in b? {}", b.can_hold(&a));
}

Debug attribute and println!

#[derive(Debug)]
struct Rectangle {
    width: u32,
    height: u32,
}
 
fn main() {
    let rect1 = Rectangle {
        width: 30,
        height: 50,
    };
 
    println!("rect1 is {:?}", rect1);
 
    // Or with pretty print :#?
    println!("rect1 is {:#?}", rect1);
}

Using dbg! macro in struct assignment can be done as dbg! returns ownership of the expression value.

#[derive(Debug)]
struct Rectangle {
    width: u32,
    height: u32,
}
 
fn main() {
    let scale = 2;
    let rect1 = Rectangle {
        width: dbg!(30 * scale),
        height: 50,
    };
 
    dbg!(&rect1);
}
rust.1720728347.txt.gz · Last modified: 2024/07/11 20:05 by utedass

Except where otherwise noted, content on this wiki is licensed under the following license: CC0 1.0 Universal
CC0 1.0 Universal Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki