英文:
Is it possible to write this program without using lifetime parameter?
问题
pub fn anagrams_for<'a>(word: &'a str, possible_anagrams: &'a [&'a str]) -> Vec<&'a str>
英文:
Is it possible to write this program without using the lifetime parameter in
pub fn anagrams_for<'a>(word: &'a str,
possible_anagrams: &'a [&'a str]) -> Vec<&'a str>
?
main.rs
pub fn is_anagram(one_word: &str, other_word: &str) -> bool {
if one_word.len() != other_word.len() {
return false;
}
for ch in one_word.chars() {
if other_word.find(ch) == None {
return false;
}
}
true
}
pub fn anagrams_for<'a>(word: &'a str, possible_anagrams: &'a [&'a str]) -> Vec<&'a str> {
let mut return_list = Vec::new();
for &item_str in possible_anagrams.iter() {
if is_anagram(word, item_str) {
return_list.push(item_str);
}
}
return_list
}
fn main() {
let word = "inlets";
let inputs = ["hello", "world", "listen", "pants"];
println!("{:?}", anagrams_for(word, &inputs));
}
答案1
得分: 1
Sort of. The program as written can use a 'static lifetime.
pub fn anagrams_for(word: &str, possible_anagrams: &[&'static str]) -> Vec<&'static str> {
However, this is overly restrictive. The correct way to write it is like this.
pub fn anagrams_for<'a>(word: &str, possible_anagrams: &[&'a str]) -> Vec<&'a str> {
This function can always be used in place of the first function.
It's important to understand that every reference in a function signature always has a lifetime. Much of the time, these are inferred, but there is always an equivalent function that assigns lifetimes to every reference. The previous function is the same as this.
pub fn anagrams_for<'a, 'b, 'c>(word: &'b str, possible_anagrams: &'c [&'a str]) -> Vec<&'a str> {
英文:
Sort of. The program as written can use a 'static
lifetime.
pub fn anagrams_for(word: &str, possible_anagrams: &[&'static str]) -> Vec<&'static str> {
However, this is overly restrictive. The correct way to write it is like this.
pub fn anagrams_for<'a>(word: &str, possible_anagrams: &[&'a str]) -> Vec<&'a str> {
This function can always be used in place of the first function.
It's important to understand that every reference in a function signature always has a lifetime. Much of the time, these are inferred, but there is always an equivalent function that assigns lifetimes to every reference. The previous function is the same as this.
pub fn anagrams_for<'a, 'b, 'c>(word: &'b str, possible_anagrams: &'c [&'a str]) -> Vec<&'a str> {
答案2
得分: 1
从生命周期省略规则来看,这是不可能的:
> 输入位置中的每个省略的生命周期都变成了一个不同的生命周期参数。这是fn
定义的当前行为。
(要理解这一点,您可能需要查看生命周期位置)
根据规则,您的函数定义将有3个不同的生命周期参数。
pub fn anagrams_for(word: &str, possible_anagrams: &[&str]) -> Vec<&str>
拥有3个不同的生命周期参数是可以的,但是Rust无法选择应该用于输出位置 -> Vec<&str>
的哪个参数。
需要使用输入位置中的一个生命周期(或者更小的生命周期)来用于输出位置(当然,它应该是与返回值相关的生命周期),除非您没有返回'static
生命周期,尽管在这种情况下,您应该明确声明为Vec<&'static str>
(这与所有权和借用以及悬垂指针相关)。
注意: 在这里,更小的 是指包含在从输入位置选择的生命周期中的生命周期。
还有一条规则可能需要检查:
> 如果存在多个输入生命周期位置,但其中一个是 &self
或 &mut self
,则self
的生命周期将分配给所有省略的输出生命周期。
这意味着像这样的代码将适用于生命周期省略,但只能从 &self
返回某些内容,而不能从其他位置返回。
struct SomeStruct;
impl SomeStruct {
pub fn anagrams_for(&self, word: &str, possible_anagrams: &[&str]) -> Vec<&str> {
//...
//返回的值应该与`&self`相关
}
}
英文:
It is not possible, from lifetime elision rules :
> Each elided lifetime in input position becomes a distinct lifetime parameter. This is the current behavior for fn
definitions.
(To understand that you might want to check lifetime positions)
According to rules, your function's definition will have 3 distinct lifetime parameter.
pub fn anagrams_for(word: &str, possible_anagrams: &[&str]) -> Vec<&str>
It is ok to have 3 distinct lifetime parameter but Rust is not able to choose which parameter should be used for the output position -> Vec<&str>
.
One of the lifetime(or smaller) from input positions needs to be used on output position(of course it should be the lifetime that related with the returned value), unless you are not returning 'static
lifetime, though you should explicitly declare that as Vec<&'static str>
(this topic is related of ownership and borrowing, dangling pointers)
Note: By smaller I meant a lifetime that contained by the selected lifetime from input positions.
There is also one rule you might want to check
> If there are multiple input lifetime positions, but one of them is &self or &mut self, the lifetime of self is assigned to all elided output lifetimes.
This means code like this will work for lifetime elision, but you can only return something from the &self
, not from the others.
struct SomeStruct;
impl SomeStruct {
pub fn anagrams_for(&self, word: &str, possible_anagrams: &[&str]) -> Vec<&str> {
//...
//return value(s) should be related with `&self`
}
}
答案3
得分: 1
回答
你需要包括生命周期参数,因为在这里生命周期省略无法发生。编译器生成的错误包含了原因,即Rust无法确定返回值是从word
还是possible_anagrams
中借用的。
一个隐藏的问题
虽然你已经添加了生命周期以满足编译器的要求,但可能存在意外的副作用。考虑以下情况:
let inputs = ["hello", "world", "listen", "pants"];
let matches = {
// 假装这是获取用户输入的操作。
let word = String::from("inlets");
anagrams_for(&word, &inputs)
};
println!("{matches:?}");
这段代码不会编译,因为根据函数签名,anagrams_for
的返回值从 word
借用,并且 word
的生命周期不够长。但实际上这并不重要,因为我们知道我们并没有从 word
借用。因此,让我们更新函数签名以解决这个问题:
pub fn anagrams_for<'a>(word: &str, possible_anagrams: &[&'a str]) -> Vec<&'a str> {
let mut return_list = Vec::new();
for &item_str in possible_anagrams.iter() {
if is_anagram(word, item_str) {
return_list.push(item_str);
}
}
return_list
}
在这里,返回值的生命周期与possible_anagrams
中的&str
相同,这意味着它不再受限于测试单词的生命周期。
无关的说明:
anagrams_for
的函数体也可以写成:
possible_anagrams
.iter()
.map(|ana| *ana)
.filter(|ana| is_anagram(word, ana))
.collect()
英文:
Answer
You do need to include the lifetime parameter because lifetime elision can’t take place here. The error that the compiler generates includes the reason, which is that Rust can’t tell whether the returned value is borrowed from word
or possible_anagrams
.
A Hidden Problem
While the way that you have added the lifetimes does appease the compiler, there’s likely an unintended side-effect. Consider:
let inputs = ["hello", "world", "listen", "pants"];
let matches = {
// Pretend this was getting user input.
let word = String::from("inlets");
anagrams_for(&word, &inputs)
};
println!("{matches:?}");
This won’t compile, because according to the function signature the return value of anagrams_for
borrows from word
, and word
doesn’t live long enough. This shouldn’t matter though, because we know we aren’t borrowing from word. So let’s update the function signature to work:
pub fn anagrams_for<'a>(word: &str, possible_anagrams: &[&'a str]) -> Vec<&'a str> {
let mut return_list = Vec::new();
for &item_str in possible_anagrams.iter() {
if is_anagram(word, item_str) {
return_list.push(item_str);
}
}
return_list
}
Here the lifetime of the return value is the same as the &str
in possible_anagrams
, which means it’s no longer bound to the lifetime of the test word.
Unrelated note:
The body of anagrams_for
can also be written as:
possible_anagrams
.iter()
.map(|ana| *ana)
.filter(|ana| is_anagram(word, ana))
.collect()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论