用字符串数组折叠

问题描述

我尝试了一些类似这样的代码:

fn main() {
   let a = vec!["May","June"];
   let s = a.iter().fold("",|s2,s3|
      s2 + s3
   );
   println!("{}",s == "MayJune");
}

结果:

error[E0369]: cannot add `&&str` to `&str`
 --> a.rs:4:10
  |
4 |       s2 + s3
  |       -- ^ -- &&str
  |       |  |
  |       |  `+` cannot be used to concatenate two `&str` strings
  |       &str
  |
help: `to_owned()` can be used to create an owned `String` from a string
reference. String concatenation appends the string on the right to the string
on the left and may require reallocation. This requires ownership of the string
on the left
  |
4 |       s2.to_owned() + s3
  |       ^^^^^^^^^^^^^

好的,很公平。因此,我将代码更改为完全相同的代码。但是然后我得到了:

error[E0308]: mismatched types
 --> a.rs:4:7
  |
4 |       s2.to_owned() + s3
  |       ^^^^^^^^^^^^^^^^^^
  |       |
  |       expected `&str`,found struct `std::string::String`
  |       help: consider borrowing here: `&(s2.to_owned() + s3)`

好的,很公平。因此,我将代码更改为完全相同的代码。但是然后我得到了:

error[E0515]: cannot return reference to temporary value
 --> a.rs:4:7
  |
4 |       &(s2.to_owned() + s3)
  |       ^--------------------
  |       ||
  |       |temporary value created here
  |       returns a reference to data owned by the current function

为什么Rust会提出虚假建议,我想做的可能吗? 请注意,我宁愿避免使用诸如“仅使用join”之类的建议, 因为这个问题旨在解决更普遍的问题。锈版本:

rustc 1.46.0 (04488afe3 2020-08-24)

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)