These are chat archives for rust-lang/rust

5th
Oct 2016
Simon Soriano
@simon0191
Oct 05 2016 02:29
Hi everyone! I want to filter all the chars of a string that match 2 chars in a tuple. I wrote this function but I'm getting the error the trait bound&char: std::cmp::PartialEq<char>is not satisfied
fn gen_str(word: String,pair: (char,char)) -> Vec<char> {
  word.chars().filter( |c| { c == pair.0 || c == pair.1 } ).collect()
}
Wesley Moore
@wezm
Oct 05 2016 03:07
Try the following. c is a char reference (&char), *c dereferences it to char so it can be compared with the chars in pair.
fn gen_str(word: String, pair: (char,char)) -> Vec<char> {
  word.chars().filter( |c| { *c == pair.0 || *c == pair.1 } ).collect()
}
Simon Soriano
@simon0191
Oct 05 2016 03:29
Thanks!

No I have another problem: ownership.
My function now looks like this:

fn gen_str(chars: & Vec<char>,pair: (char,char)) -> Vec<char> {
  (*chars).into_iter().filter( |&c| { c == pair.0 || c == pair.1 } ).collect()
}

But I'm getting this error:

error[E0507]: cannot move out of borrowed content
  --> main.rs:33:3
   |
33 |   (*chars).into_iter().filter( |&c| { c == pair.0 || c == pair.1 } ).collect()
   |   ^^^^^^^^ cannot move out of borrowed content
I still don't understand the ownership system. How can I make that function work?
Wesley Moore
@wezm
Oct 05 2016 03:52
into_iter tries to turn chars into an iterator, thus taking ownership of it. However chars is borrowed as indicated by &Vec char in the parameters. Try chars.iter, which will provide references to the chars in the vec
If you haven't read it already the ownership chapter from the book and the following chapter on borrowing and references may help shore up your understanding
Simon Soriano
@simon0191
Oct 05 2016 04:09
@wezm how did you know that into_iter takes ownership of chars?
it is a self method, not &self, so it takes ownership of self
in general into_anything takes ownership
Simon Soriano
@simon0191
Oct 05 2016 04:12
ok, thanks :)
Jonas Platte
@jplatte
Oct 05 2016 06:10
@simon0191 Also you can always write x.method() instead of (*x).method(), see Deref Coercions in the rust book.