mkaz.blog

Working with Rust

Structs

In Rust, structs are a custom data type. Rust is not truly object-oriented, but structs can be used in a similar manner. See Chapter 5 and Chapter 17 in the Rust Book for additional details.

Defining Struct

Here is how to define and use a basic struct.

struct Point {
    x: i32,
    y: i32,
}
 
fn main() {
    let pt = Point{ x: 5, y: 8 };
    println!("Point: ({}, {})", pt.x, pt.y);
}

Output a Struct

For debugging, it is often useful to print out a struct to see what it contains. The following will give an error cannot be formatted with the default formatter since Rust does not inherently know what to do.

let pt = Point{ x: 5, y: 8 };
println!("{:?}", pt);

Add the derive(Debug) to a struct definition, and Rust will output name and fields.

#[derive(Debug)]
struct Point {
    x: i32,
    y: i32,
}
 
fn main() {
    let pt = Point{ x: 5, y: 8 };
    println!("{:?}", pt);
    // Output: Point { x: 5, y: 8 }
}

You can define a custom output format by implementing fmt::Display for the struct, see in Rust by Example here.

Implement a method for struct

Define a method on a struct using impl {} on the struct and define the functions within.

#[derive(Debug)]
struct Point {
    x: i32,
    y: i32,
}
 
impl Point {
    fn add(&self, other: &Point) -> Point {
        Point{ x:self.x + other.x, y: self.y + other.y }
    }
}
 
fn main() {
    // assign value when instantiate
    let p1 = Point{ x: 5, y: 8 };
    let p2 = Point{ x: 2, y: -1 };
    println!("{:?}", p1.add(&p2));
}

Define operator on custom struct

The + operator uses the Add traits from std::ops. Implement this trait for a struct to use for example: point1 + point2. For additional info see Traits in Rust book and for additional operator traits, see std::ops documentation.

use std::ops::Add;
 
#[derive(Debug)]
struct Point {
    x: i32,
    y: i32,
}
 
impl Add for Point {
    type Output = Self;
 
    fn add(self, other: Self) -> Self {
        Point{ x:self.x + other.x, y: self.y + other.y }
    }
}
 
fn main() {
    // assign value when instantiate
    let p1 = Point{ x: 5, y: 8 };
    let p2 = Point{ x: 2, y: -1 };
    println!("{:?}", p1 + p2);
}