0

This code:

fn main() { let input = String::from("The quick brown fox"); for s in input.split(" ") { let s2: String = s; println!("{:?}", s2) } } 

gives me this error:

error[E0308]: mismatched types --> src\main.rs:8:26 | 8 | let s2: String = s; | ------ ^ | | | | | expected struct `std::string::String`, found `&str` | | help: try using a conversion method: `s.to_string()` | expected due to this 

Do I have to do what the compiler recommends (converting s inside the loop) or can I change the loop so that I get Strings from the splitting directly?

6
  • play.rust-lang.org/… Commented Mar 13, 2020 at 10:18
  • @Stargateur The question you linked doesn't really help because I know how to convert it, but I wanted to know if I can do it inside the loop header. Your Playground link on the other hand seems to be the answer to my question. :) Commented Mar 13, 2020 at 10:21
  • @Stargateur Sorry, which rule are you referring to? Include the fn main() to make it a MWE? I will do that next time, my apologies. Commented Mar 13, 2020 at 10:23
  • doc.rust-lang.org/std/str/struct.Split.html#implementations, please check the Iterator implementation it always yields &str, it is better if you specify why you need this done internally ? Commented Mar 13, 2020 at 10:24
  • @ÖmerErden Just learning about the capabilities of Rust. Because the left side of in is some kind of pattern I'm not really clear yet on what is possible there. Commented Mar 13, 2020 at 10:26

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.