简体   繁体   中英

How to split line in Rust

I want create a function that split and return vector. I'm trying change line type, but its dont help.

Code:

pub fn format(&self, basic_line: String) -> Vec<&str> {
    let temp_line = basic_line.trim().to_lowercase();
    return temp_line.split_whitespace().collect();
}

Error Output:

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`

to_uppercase/to_lowercase return an owned String , so you cannot return a Vec<&str> , it is invalidated because those &str points to the function scoped created strings, return a Vec<String> instead:

pub fn format(basic_line: &str) -> Vec<String> {
    basic_line
        .trim()
        .split_whitespace()
        .map(str::to_lowercase)
        .collect()
}

Playground

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM