Struct Derive Trait Capabilities

Unlock Debug, Clone, PartialEq and Default on structs with a single derive line, and see what each trait actually buys you.

RustData Integrity

Code

rustsnippet
27 lines
#[derive(Debug, Clone, PartialEq, Default)]
struct Config {
    host: String,
    port: u16,
    verbose: bool,
}

fn main() {
    // Default:零值构造
    let base = Config::default();
    println!("default: {:?}", base);

    let custom = Config {
        host: String::from("localhost"),
        port: 8080,
        verbose: true,
    };

    // Clone:显式复制
    let copy = custom.clone();

    // PartialEq:逐字段相等
    println!("same: {}", custom == copy);

    // Debug:一键结构化打印
    println!("custom: {:?}", custom);
}

How the snippet works

Struct Derive Trait Capabilities is built around the function main.

Applying it

The demo output is labeled (default:, same:, custom:), so every printed line maps back to its originating operation.

Statements that matter

let base = Config::default();
let copy = custom.clone();

Interactive Tools for This Topic

FAQ

What does Struct Derive Trait Capabilities print when run?
Execute the whole file; each printed line is prefixed with a label like `default:`, `same:`, `custom:`.