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?

Stargateur
  • 24,473
  • 8
  • 65
  • 91
AndreKR
  • 32,613
  • 18
  • 106
  • 168
  • https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=ae330f959358a0ae2460dbd1f52c2cee – Stargateur Mar 13 '20 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. :) – AndreKR Mar 13 '20 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. – AndreKR Mar 13 '20 at 10:23
  • https://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 ? – Ömer Erden Mar 13 '20 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. – AndreKR Mar 13 '20 at 10:26
  • Yes it is a pattern, you can see it from the [reference](https://doc.rust-lang.org/reference/expressions/loop-expr.html#iterator-loops), also you can do something like this : https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=3eea90662f106c2273a842d4aea29e93, (edit:I haven't seen it is done by @Stargateur before, it is just same) – Ömer Erden Mar 13 '20 at 10:35

0 Answers0