首页 > 解决方案 > 我可以直接从拆分中获取字符串吗?

问题描述

这段代码:

fn main() {
    let input = String::from("The quick brown fox");

    for s in input.split(" ") {
        let s2: String = s;
        println!("{:?}", s2)
    }
}

给我这个错误:

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

我是否必须按照编译器的建议进行操作(s在循环内进行转换),或者我可以更改循环以便String直接从拆分中获得 s 吗?

标签: stringrust

解决方案


推荐阅读