How to print an array and a vector?
Asked Answered
E

2

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"]
Exemplify answered 26/6, 2015 at 16:22 Comment(3)
have you seen #30253922 ?Witchery
Additionally, please read How do I ask a good question?. In this example, you should include what you have already tried. It would be even better to include a MCVE. I'd also highly recommend reading The Rust Programming Language, which the team has spent a lot of time on.Harder
thanks for the recommendations.Exemplify
A
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.

Altagraciaaltaic answered 26/6, 2015 at 16:29 Comment(1)
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?Westonwestover
G
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]

}

Gallstone answered 13/1, 2022 at 8:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.