【发布时间】:2017-12-12 02:30:17
【问题描述】:
我在 Rust 中有以下代码。我知道我不应该返回对局部变量的引用,在这种情况下我不是。要拆分的字符串作为&str 引用传递,在确定拆分边界后,我返回&s[0..idx],其中idx 是边界的结尾。我确信这不会导致“悬空”参考相关错误。然而,事实证明我错了!
fn demo4() {
let mut s = String::from("Elijah Wood");
let firstname = str_split(&s, &String::from(" "));
println!("First name of actor: {}", firstname);
}
// can handle both &str and &String
fn str_split(s: &str, pat: &str) -> &str {
let bytes = s.as_bytes();
let b_pat = pat.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b_pat {
return &s[0..i];
}
}
&s[..]
}
fn main() {
demo4();
}
我收到以下错误:
error[E0106]: missing lifetime specifier
--> src/main.rs:7:37
|
7 | fn str_split(s: &str, pat: &str) -> &str {
| ^ expected lifetime parameter
|
= help: this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from `s` or `pat`
非常感谢任何解释。
【问题讨论】:
-
@trentcl 如果快照给您带来困扰,我深表歉意。当时似乎是最好的主意
-
错误消息最好在文本中包含,不仅适用于潜在的回答者,也适用于可能有相同问题的未来提问者。没什么大不了的。
-
@trentcl 我明白你的意思。关于编译器错误原因的任何指针?