Skip to content

Instantly share code, notes, and snippets.

@patshaughnessy
Last active November 22, 2020 23:39
Show Gist options
  • Save patshaughnessy/3252e2e718445d991499e5cd08e1949c to your computer and use it in GitHub Desktop.
Save patshaughnessy/3252e2e718445d991499e5cd08e1949c to your computer and use it in GitHub Desktop.
Rust Vec<String> find example
fn main() {
let needle = "list".to_string();
let haystack = ["some".to_string(), "long".to_string(), "list".to_string(), "of".to_string(), "strings".to_string()].to_vec();
if let Some(str) = haystack.iter().find(|&s| *s == needle) {
println!("{}", needle);
} else {
println!("Nothing there...");
}
}
@patshaughnessy
Copy link
Author

Thanks all of you for the ideas!

Yup as I learned on StackOverflow, using contains seems a lot simpler and cleaner in this example. Using into_iter will also work, but isn't what I need in my app because I don't want to move the data out.

And thanks for the type inference tip - yes much cleaner.

The deeper issue for me is that Rust's & and && syntax can be very confusing, especially with iterators and closures. Will just take some getting used to I suppose :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment