Rust Programming: Functionality with Derived Traits

0
In Rust, we can add useful functionality to our types by using derived traits. A derived trait is a trait that the compiler can automatically implement for our type. One useful derived trait is Debug, which allows us to print our type in a way that is useful for debugging. To add the Debug trait to our type, we use the #[derive(Debug)] attribute. For example, the following code defines a struct called `Rectangle` and adds the Debug trait to it:

#[derive(Debug)]
struct Rectangle {
    width: u32,
    height: u32,
}

Now, we can print a `Rectangle` instance using the `{:?}` placeholder in a `println!()` macro:

let rect1 = Rectangle {
    width: 30,
    height: 50,
};

println!("rect1 is {:?}", rect1);

This will print the following output:

rect1 is Rectangle { width: 30, height: 50 }

As you can see, the `{:?}` placeholder prints the values of all the fields in the `Rectangle` struct. This can be helpful when we are debugging our code and need to see the values of the variables in our program.

Another way to print a value using the Debug format is to use the `dbg!()` macro. The `dbg!()` macro takes an expression as its argument and prints the value of that expression to the standard error stream (stderr). The following code shows how to use the `dbg!()` macro:

let scale = 2;
let rect1 = Rectangle {
    width: dbg!(30 * scale),
    height: 50,
};

dbg!(&rect1);

This code will print the following output to the standard error stream:

[src/main.rs:10] 30 * scale = 60
[src/main.rs:14] &rect1 = Rectangle {
    width: 60,
    height: 50,
}

The first line of output shows the value of the expression `30 * scale`, which is 60. The second line of output shows the value of the struct `rect1`. The `dbg!()` macro can be very helpful when we are debugging our code and need to see the values of variables or expressions.

Post a Comment

0Comments
Post a Comment (0)