4

I am new to Rust, and I am struggling with a simple task. I'd like to convert a matrix into a string, with the fields separated by tabs. I think this is possible by using the map function or something similar, but right now whatever I try gives me an error.

This is what I have, and I'd like to convert the col part into function, which returns a tab separated string, which I can print. In Python this is something like row.join("\t"). Is there something similar in Rust?

fn print_matrix(vec: &Vec<Vec<f64>>) { for row in vec.iter() { for col in row.iter() { print!("\t{:?}",col); } println!("\n"); } } 
3
  • What part of this doesn't work? Can you provide a minimal, complete, example on the Playpen? There doesn't seem to be anything wrong with this code. Commented Mar 20, 2016 at 8:56
  • it should print string<tab>string<tab>string but it prints a leading tab. there must be a more elegant solution than that, without fiddling Commented Mar 20, 2016 at 9:09
  • Look at the examples under doc.rust-lang.org/std/fmt/#format_args Commented Mar 20, 2016 at 9:28

2 Answers 2

7

There is indeed a join in the standard library, but it's not super useful (often additional allocation is required). But you can see a solution here:

fn print_matrix(vec: &Vec<Vec<f64>>) { for row in vec { let cols_str: Vec<_> = row.iter().map(ToString::to_string).collect(); let line = cols_str.join("\t"); println!("{}", line); } } 

The problem is that this join works with slices and not with iterators. We have to convert all elements into a string first, collect the result in a new vector and can use join then.

The crate itertools defines a join method for iterators and can be applied like so:

for row in vec { let line = row.iter().join("\t"); println!("{}", line); } 

And to avoid using any of the named functionality, you can of course do it manually:

for row in vec { if let Some(first) = row.get(0) { print!("{}", first); } for col in row.iter().skip(1) { print!("\t{}", col); } println!(""); } 
Sign up to request clarification or add additional context in comments.

Comments

4

Besides join from itertools you could always use fold on iterator (which is really useful), like this:

row.iter().fold("", |tab, col| { print!("{}{:?}", tab, col); "\t" }); 

1 Comment

This will end with one extra \t

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.