How to print structs and arrays?
Asked Answered
V

6

122

How do I print structs and arrays in Rust? Other languages are able to print structs and arrays directly.

struct MyStruct {
    a: i32,
    b: i32
}

and

let arr: [i32; 10] = [1; 10];
Vulgarity answered 15/5, 2015 at 7:0 Comment(2)
Rust has a different philosophy than Go: where Go is "batteries included", Rust is "do not pay for what you do not use". Thus, if you wish to print MyStruct, you have to ask the compiler to include the code to print it (or code it yourself).Stalder
@MatthieuM. this is actually the right answer (with a great context in relation to Go). Post and I'll upvote.Youth
G
175

You want to implement the Debug trait on your struct. Using #[derive(Debug)] is the easiest solution. Then you can print it with {:?}:

#[derive(Debug)]
struct MyStruct{
    a: i32,
    b: i32
}

fn main() {
    let x = MyStruct{ a: 10, b: 20 };
    println!("{:?}", x);
}
Gameness answered 15/5, 2015 at 7:7 Comment(3)
can we use Debug trait for arrays?Vulgarity
@Vulgarity the Debug trait is already implemented for many types, including arrays from 0 to 32 items, as well as slices and Vec of any length. The important thing is that the item inside the container must also implement Debug.Renfred
It is also possible to pretty print in debug mode using the same trait #[derive(Debug)] as shown in above answer, while replacing {:?} with {:#?} in println! macro. Details can be found in Rust Book Ch-5Responsive
A
37

As mdup says, you can use Debug, but you can also use the Display trait.

All types can derive (automatically create) the fmt::Debug implementation as #[derive(Debug)], but fmt::Display must be manually implemented.

You can create a custom output:

struct MyStruct {
    a: i32,
    b: i32
}

impl std::fmt::Display for MyStruct {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "(value a: {}, value b: {})", self.a, self.b)
    }
}

fn main() {
    let test = MyStruct { a: 0, b: 0 };

    println!("Used Display: {}", test);    
}

Shell:

Used Display: (value a: 0, value b: 0)

For more information, you can look at the fmt module documentation.

Ami answered 6/4, 2016 at 0:32 Comment(0)
G
13

As no one here explicitly answers for arrays, to print out an array you need to specify the {:?}, also used to print debug output

let val = 3;
let length = 32; // the maximum that can be printed without error
let array1d = [val; length];
let array2d = [array1d; length]; // or [[3; 32]; 32];
let array3d = [array2d; length]; // or [[[3; 32]; 32]; 32];

However arrays where length > 32 will exit with an error:

let length = 33;
let array1d = [3; length];
println("{:?}", array1d);

error[E0277]: the trait bound `[{integer}; 33]: std::fmt::Debug` is not satisfied
--> src\main.rs:6:22
|
|     println!("{:?}", array1d);
|                      ^^^^^^^ the trait `std::fmt::Debug` is not implemented for `[{integer}; 33]`

Longer arrays can be printed out with the approach from this answer: Implement Debug trait for large array type

Galang answered 10/6, 2017 at 18:0 Comment(0)
M
10

If you want your output to be formatted properly with indentation, you can use {:#?}.

#[derive(Debug)]
struct MyStruct{
    a: i32,
    b: i32
}

fn main() {
    let x = MyStruct{ a: 10, b: 20 };
    println!("{:#?}", x);
}

Output:

MyStruct {
    a: 10,
    b: 20,
}
Minorite answered 7/10, 2022 at 2:56 Comment(0)
U
8

Actually just {:?} is sufficient.

let a = [1, 2, 3, 4, 5];
let complete = &a[..];
println! ("{:?}", a);
println! ("{:?}", complete);
Unblock answered 27/12, 2017 at 0:37 Comment(2)
This is not true for structs. It only works for arrays.Furtive
And it only works for arrays whose inner elements implement the Debug trait.Stalder
F
0
#[derive(Debug)]
 struct Rectangle{
       width: u32,
       height: u32,
  }

fn main(){
   let rec = Rectangle{
      width: 50,
      height: 30,
   };

   println!("The rectangle {:?} ", rec);
   println!("The area of the rectangle is {} pixels", 
   area_rectangle(&rec));
}

fn area_rectangle(rectangle: &Rectangle) -> u32{
    rectangle.width * rectangle.height
}
Ferrell answered 16/7, 2020 at 8:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.