vector of string slices goes out of scope but original string remains, why is checker saying there is an error?

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

vector of string slices goes out of scope but original string remains, why is checker saying there is an error?

问题

初学者学习 Rust。我明白下面的代码为什么会出现错误。test(x) 创建了 y,然后返回一个引用了 y 拥有的 &str 值的值。当 y 超出作用域时,它被销毁,因此不能这样做。

这里我的问题是,y 拥有的 &str 实际上是 x 的一个切片,它还没有超出作用域... 所以从技术上讲,引用应该仍然有效。

enum TestThing<'a> {
    Blah(&'a str)
}

fn test(x: &str) -> Vec<TestThing> {
    let y = x.split(" ").collect::<Vec<&str>>();
    parse(&y)
}

fn parse<'a>(x: &'a Vec<&str>) -> Vec<TestThing<'a>> {
    let mut result: Vec<TestThing> = vec![];
    for v in x {
        result.push(TestThing::Blah(v));
    }
    result
}

这里的检查器是否过于严格?是否有解决方法?我是否遗漏了什么?这是否与 split 有关?我还尝试过克隆 v,但也没有成功。

英文:

Beginner at rust here. I understand why the code below has an error. test(x) creates y then returns a value that references the &str owned by y. y is destroyed as it goes out of scope so it can't do that.

Here's my issue the thing is the &str owned by y is actually a slice of x that has NOT went out of scope yet... so technically the reference should still work.

enum TestThing&lt;&#39;a&gt; {
    Blah(&amp;&#39;a str)
}

fn test(x: &amp;str) -&gt; Vec&lt;TestThing&gt; {
    let y = x.split(&quot; &quot;).collect::&lt;Vec&lt;&amp;str&gt;&gt;();
    parse(&amp;y)
}

fn parse&lt;&#39;a&gt;(x: &amp;&#39;a Vec&lt;&amp;str&gt;) -&gt; Vec&lt;TestThing&lt;&#39;a&gt;&gt; {
    let mut result: Vec&lt;TestThing&gt; = vec![];
    for v in x {
        result.push(TestThing::Blah(v));
    }
    result
}

Is the checker just being over-zealous here? Is there a method around this? Am I missing something? Is this just something to do with split? I also tried cloning v, and that didn't work either.

答案1

得分: 3

将生命周期移到这里:x: &amp;&#39;a Vec&lt;&amp;str&gt; -> x: &amp;Vec&lt;&amp;&#39;a str&gt;

英文:

Move the lifetime here: x: &amp;&#39;a Vec&lt;&amp;str&gt; -> x: &amp;Vec&lt;&amp;&#39;a str&gt;.

P.S. Using a slice (&amp;[&amp;&#39;a str]) would be better, since it's smaller and more flexible, see https://stackoverflow.com/questions/40006219/why-is-it-discouraged-to-accept-a-reference-to-a-string-string-vec-vec-o. Some kind of impl Iterator or impl IntoIterator would be even more flexible.

huangapple
  • 本文由 发表于 2023年2月18日 03:36:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/75488576.html
匿名

发表评论

匿名网友

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

确定