英文:
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<'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
}
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: &'a Vec<&str>
-> x: &Vec<&'a str>
。
英文:
Move the lifetime here: x: &'a Vec<&str>
-> x: &Vec<&'a str>
.
P.S. Using a slice (&[&'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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论