let us look at area of a square in rust using struct & methods
main.rs
use std::fmt;
struct Square {
side: i32
}
impl fmt::Display for Square {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Square of side {}", self.side)
}
}
impl Square {
fn area(&self) -> i32 {
let x = self.side;
x*x
}
}
fn main() {
let square = Square { side: 4 };
println!("{}", square.to_string());
println!("Square area: {}", square.area());
}
Cargo.toml
[package] name = "rust_square" version = "0.1.0" authors = ["bhagvan.kommadi"] edition = "2018" [dependencies]
Run the following command:
cargo run
The screenshot of the output will look like this:
