5

I'm playing with Rust and I wonder how I can print an array and a vector.

let a_vector = vec![1, 2, 3, 4, 5];
let an_array = ["a", "b", "c", "d", "e"];

I want to print on the screen and the result should be something like:

[1, 2, 3, 4, 5]
["a", "b", "c", "d", "e"]

In python it is:

lst = ["a", "b", "c", "d", "e"]
print lst

and printing it would show:

["a", "b", "c", "d", "e"]
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Ranj
  • 718
  • 1
  • 12
  • 19
  • 2
    have you seen http://stackoverflow.com/questions/30253422/how-to-print-structs-and-arrays ? – oli_obk Jun 26 '15 at 16:29
  • Additionally, please read [How do I ask a good question?](/help/how-to-ask). In this example, you should include *what you have already tried*. It would be even better to include a [MCVE](/help/mcve). I'd also **highly** recommend reading [*The Rust Programming Language*](http://doc.rust-lang.org/stable/book/), which the team has spent a lot of time on. – Shepmaster Jun 26 '15 at 19:59
  • thanks for the recommendations. – Ranj Jul 21 '15 at 11:42

2 Answers2

13
println!("{:?}", a_vector);
println!("{:?}", an_array);

The {:?} is used to print types that implement the Debug trait. A regular {} would use the Display trait which Vec and arrays don't implement.

A.B.
  • 15,364
  • 3
  • 61
  • 64
  • 2
    That works only for arrays up to 32 ("arrays only have std trait implementations for lengths 0..=32"). Is there an easy way to print content of longer arrays? – Qinto Jun 21 '20 at 09:33
0
fn main() {

let v = vec![12; 4]; let v1 = vec![7; 5];

//1. In general, the {} will be automatically replaced with any // arguments in order of their placement. These will be stringified.

println!("{:?}", v);

println!("First vector: {0:?} and Second vector: {1:?} ", v, v1);

//Results above //[12, 12, 12, 12]

//First vector: [12, 12, 12, 12] and Second vector: [7, 7, 7, 7, 7]

//2.With Positional arguments

 println!("{0:?}", v);

 println!("First vector: {0:?} and Second vector: {1:?}  ", v, v1);

// Results above

//[12, 12, 12, 12]

//First vector: [12, 12, 12, 12] and Second vector: [7, 7, 7, 7, 7]

//2.You could assign variables for Positional arguments as well

 println!("{var1:?}", var1 =v);

 println!("First vector: {var1:?} and Second vector: {var2:?}  ", var1=v, var2=v1);

// Results above

//[12, 12, 12, 12]

//First vector: [12, 12, 12, 12] and Second vector: [7, 7, 7, 7, 7]

}

geobudex
  • 536
  • 1
  • 8
  • 24