rust
This is an old revision of the document!
Table of Contents
Rust
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 square(size: u32) -> Self { Self { width: size, height: size, } } }
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.1720642953.txt.gz · Last modified: 2024/07/10 20:22 by utedass
