Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print structs and arrays?

Tags:

rust

Go seems to be able to print structs and arrays directly.

struct MyStruct {     a: i32,     b: i32 } 

and

let arr: [i32; 10] = [1; 10]; 
like image 742
tez Avatar asked May 15 '15 07:05

tez


People also ask

How do you print an array in Rust?

To print an array in Rust, we use the 😕 Operator inside the println! function.


2 Answers

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); } 
like image 173
mdup Avatar answered Sep 20 '22 09:09

mdup


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.

like image 37
Angel Angel Avatar answered Sep 20 '22 09:09

Angel Angel