找到的翻译部分: “expected struct `String` found struct `Vec<&String>`”

huangapple go评论60阅读模式
英文:

expected struct `String` found struct `Vec<&String>`

问题

您的代码中有一些错误,我会帮助您进行修正,以下是修正后的代码:

fn reverse_words(words: &str) -> String {
    let mut split = words.split_whitespace();
    let vec: Vec<&str> = split.collect();
    let mut vec2 = Vec::new();
    for word in vec {
        vec2.push(word.chars().rev().collect::<String>());
    }
    return vec2.join(" ");
}

在修正后的代码中,我做了以下更改:

  1. &amp; 替换为正常的 &,以使代码有效。
  2. 修正了 vec2 的类型,将其更改为 Vec<String>,以存储反转后的单词。
  3. 使用 join 方法将反转后的单词连接成一个字符串,并在单词之间添加空格。

这样,您的函数应该能够将输入的字符串中的单词反转,并在它们之间添加空格,然后返回一个拥有的字符串。

英文:

I have a function to reverse characters in words and I need to know how to convert a Vec<&String> into a regular owned String (with spaces between the words).

fn reverse_words(words: &amp;str) -&gt; String {
let mut split = words.split_whitespace();
let vec: Vec&lt;&amp;str&gt; = split.collect();
let vec2 = vec!();
    for word in vec {
        vec2.push(&amp;word.chars().rev().collect::&lt;String&gt;());
    }
    return vec2;
}

.

error[E0308]: mismatched types
 --&gt; src/lib.rs:8:12
  |
1 | fn reverse_words(words: &amp;str) -&gt; String {
  |                                  ------ expected `String` because of return type
...
8 |     return vec2;
  |            ^^^^ expected struct `String`, found struct `Vec`
  |
  = note: expected struct `String`
             found struct `Vec&lt;&amp;String&gt;`

For more information about this error, try `rustc --explain E0308`.
error: could not compile `challenge` due to previous error


NOTE: Line numbers in error messages can be incorrect due to concatenation.

答案1

得分: 2

以下是你的代码,经过最少的更改以使其正常工作。你只需要在最后的语句中添加.join(' ')

fn reverse_words(words: &str) -> String {
    let split = words.split_whitespace();
    let vec: Vec<&str> = split.collect();
    let mut vec2 = vec![];
    for word in vec {
        vec2.push(word.chars().rev().collect::<String>());
    }
    vec2.join(" ")
}

fn main() {
    let sentence = "hello world";
    
    assert_eq!(reverse_words(sentence), "olleh dlrow");
}

这是一个效率低下的实现,需要大量的分配。您可以链接Iterator trait的方法,以获得不需要太多分配的解决方案:

fn reverse_words(words: &str) -> String {
    words
        .split_whitespace()
        .map(|w| w.chars().rev().chain([' ']))
        .flatten()
        .take(words.len())
        .collect::<String>()
}

fn main() {
    let sentence = "hello world";

    assert_eq!(reverse_words(sentence), "olleh dlrow");
}

Playground.

英文:

Here is a version of your code with minimal changes to make it work. You basically only need to add a .join(&#39; &#39;) to your last statement:

fn reverse_words(words: &amp;str) -&gt; String {
    let split = words.split_whitespace();
    let vec: Vec&lt;&amp;str&gt; = split.collect();
    let mut vec2 = vec![];
    for word in vec {
        vec2.push(word.chars().rev().collect::&lt;String&gt;());
    }
    vec2.join(&quot; &quot;)
}


fn main() {
    let sentence = &quot;hello world&quot;;
    
    assert_eq!(reverse_words(sentence), &quot;olleh dlrow&quot;);
}

Playground.

This is an inefficient implementation requiring a lot of allocation though. You can chain methods of the Iterator trait to get a solution that does not require as much allocation:

fn reverse_words(words: &amp;str) -&gt; String {
    words
        .split_whitespace()
        .map(|w| w.chars().rev().chain([&#39; &#39;]))
        .flatten()
        .take(words.len())
        .collect::&lt;String&gt;()
}

fn main() {
    let sentence = &quot;hello world&quot;;

    assert_eq!(reverse_words(sentence), &quot;olleh dlrow&quot;);
}

Playground.

huangapple
  • 本文由 发表于 2023年2月19日 11:09:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/75497758.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定