Get the debug output as a string

Is there a way I can do this?

#[derive(Debug)]
struct Ax {
    n: i32,
    m: i32
}
let ax = Ax { n: 1, m: 2 };
println!("{:?}", ax);
// thel last line output: Ax { n: 1, m: 2 }


let ax_fmt = ax.fmt();
assert_eq!(ax_fmt, "Ax { n: 1, m: 2 }"); //the second paramter comes from the output

You can do format!("{:?}", ax) which returns a String.

3 Likes

let ax_fmt = format!("{ax:?}");

But note that you can't count on the output being anything in particular.

5 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.