DEV Community

Cover image for trap of fold
Peter Vivo
Peter Vivo

Posted on

trap of fold

image by Stefano Valicchia /unsplash

I would like to learn rust, but with my javascript background that philosophy not so easy. For learn this language I start solving few codewars kata, and meanwhile I put rust kernel to jupyter notebook too which is really fine.

I found this short problem: Turn to string without char repetition.I think this is was good for practice

"tttrrrappp oooof fffffooooldd"
  .chars()
  .fold("", |mut acc, ch| if acc.chars().last() == Some(ch) {acc} else {[acc, ch.to_string()].concat()})
Enter fullscreen mode Exit fullscreen mode

but this lead to this error:

.fold("", |acc, ch| if acc.chars().last() == Some(ch) {acc} else {[acc, ch.to_string()].concat()})
                                                                        ^^^^^^^^^^^^^^ expected `&str`, found struct `std::string::String`
mismatched types

Enter fullscreen mode Exit fullscreen mode

I like rust error messages, because very meaningful, except this case. After take look tons of rust example and blog about string handling finally I found the solution:

"tttrrrappp oooof fffffooooldd"
  .chars()
  .fold(String::new(), |acc, ch| if acc.chars().last() == Some(ch) {acc} else {[acc, ch.to_string()].concat()})
Enter fullscreen mode Exit fullscreen mode

fold collector will be non static!

Latest comments (0)