1 rust
我想创建一个分割并返回向量的函数。我正在尝试更改line类型,但没有帮助。
代码:
pub fn format(&self, basic_line: String) -> Vec<&str> {
let temp_line = basic_line.trim().to_lowercase();
return temp_line.split_whitespace().collect();
}
Run Code Online (Sandbox Code Playgroud)
错误输出:
error[E0515]: cannot return value referencing temporary value
--> src\module.rs:55:16
|
53 | let f_line:Vec<&str> = line.trim().to_lowercase().split_whitespace().collect();
| -------------------------- temporary value created here
54 |
55 | return f_line;
| ^^^^^^ returns a value referencing data owned by the current function
For more information about this error, try `rustc --explain E0515`
Run Code Online (Sandbox Code Playgroud)
to_uppercase/to_lowercase返回一个owned的String,所以你不能返回a Vec<&str>,它是无效的,因为它们&str指向函数作用域创建的字符串,Vec<String>而是返回a:
pub fn format(basic_line: &str) -> Vec<String> {
basic_line
.trim()
.split_whitespace()
.map(str::to_lowercase)
.collect()
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
573 次 |
| 最近记录: |