gpt4 book ai didi

rust - 为什么 `&str` 实现函数(例如 `String` )的 `String::trim` 结果不像静态字符串文字?

转载 作者:行者123 更新时间:2023-11-29 08:27:07 25 4
gpt4 key购买 nike

<分区>

考虑以下代码:

enum Inflection {
Question_NoYelling,
Question_Yelling,
Yelling_NoQuestion,
Other,
}

fn is_whitespace_or_question_mark(c: char) -> bool {
match c {
' ' => true,
'?' => true,
'\t' => true,
'\n' => true,
_ => false,
}
}

fn split_message_into_words_and_punctuation(message: &str) -> Vec<&str> {
String::from(message).split(is_whitespace_or_question_mark)
.filter(|element| element.len() != 0).collect();
}

fn is_uppercase(word: &str) -> bool {
if word != "?" && word == &word.to_string().to_uppercase() {
true
} else {
false
}
}

fn get_inflection(message: &str) -> Inflection {
let mut is_question: bool = false;
let mut is_yelling: bool = false;

let words_and_punctuation: Vec<&str> = split_message_into_words_and_punctuation(message);

for element in words_and_punctuation.iter() {
if is_uppercase(element) {
is_yelling = true;
break;
}
}

if words_and_punctuation[words_and_punctuation.len() - 1] == "?" {
is_question = true;
}

match (is_question, is_yelling) {
(true, true) => Inflection::Question_Yelling,
(true, false) => Inflection::Question_NoYelling,
(false, true) => Inflection::Yelling_NoQuestion,
(false, false) => Inflection::Other,
}
}

fn reply_to_non_empty(message: &str) -> &str {
match get_inflection(message) {
Inflection::Question_NoYelling => "Sure.",
Inflection::Question_Yelling => "Whoa, chill out!",
Inflection::Yelling_NoQuestion => "Calm down, I know what I'm doing!",
Inflection::Other => "Whatever.",
}
}

pub fn reply(message: &str) -> &str {
let message: &str = String::from(message).trim();

match message {
"" => "Fine. Be that way!",
_ => reply_to_non_empty(message),
}
}

编译器提示两个位置:

pub fn reply(message: &str) -> &str {
let message: &str = String::from(message).trim();

match message {
"" => "Fine. Be that way!",
_ => reply_to_non_empty(message),
}
}

fn split_message_into_words_and_punctuation(message: &str) -> Vec<&str> {
String::from(message).split(is_whitespace_or_question_mark)
.filter(|element| element.len() != 0).collect();
}

在这两种情况下,编译器都会说 String::from(message) 的生命周期不够长。但是,为什么 String::from(message) 的生命周期不够长,当我只用它来获取字符串文字或 Vec 最后是字符串字面量?

供引用,编译器投诉的例子:

error[E0597]: borrowed value does not live long enough
--> src\lib.rs:69:25
|
69 | let message: &str = String::from(message).trim();
| ^^^^^^^^^^^^^^^^^^^^^ - temporary value only lives until here
| |
| does not live long enough
|
|
note: borrowed value must be valid for the anonymous lifetime #1 defined on the function body at 68:1...
--> src\lib.rs:68:1
|
68 | / pub fn reply(message: &str) -> &str {
69 | | let message: &str = String::from(message).trim();
70 | |
71 | | match message {
... |
74 | | }
75 | | }
| |_^

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com