为什么在打开从用户输入给程序的路径时需要 .to_string() 方法?

Why is .to_string() method needed when opening the path given to the program from its user's input?

以下代码打开一个文件:

use std::fs;
use std::io; 

fn main() {
    
 println!("Give me the absolute path to the file you want to read.");

 let mut to_read = String::new();
 
 io::stdin().read_line(&mut to_read).expect("Failed to read line"); 
    
 to_read = to_read.trim_end().to_string();
 
 let contents = fs::read_to_string(to_read).expect("Something went wrong reading the file");
    
 println!("{}", contents.trim() ); 
    
}

what I've read 关于 .to_string() 它将给定值转换为字符串。 令我困惑的是,在我的代码中,给定值,即分配给变量 to_read 的值已经是一个字符串 在分配时:let mut to_read = String::new();。我通过发现 修补,to_read = to_read.trim_end().to_string(); 行是我的代码工作所必需的,否则 Rust 会出现消息恐慌:

'Something went wrong reading the file: Os { code: 2, kind: NotFound, message: "No such file or directory" }

为什么会这样?

trim_end returns a &str: 切片,即对初始字符串的一部分的引用。

所以如果你这样做

to_read = to_read.trim_end()

然后您试图将 &str 分配给类型为 String 的变量。

您采取的解决方案是使用 to_string()&str 构建一个新的 String。虽然这行得通,但它毫无用处,因为您稍后在 read_to_string.

中不需要 String

更好的解决方案是将 &str 保留在一个新变量中,该变量可以具有相同的名称:

use std::fs;
use std::io; 

fn main() {
    
    println!("Give me the absolute path to the file you want to read.");

    let mut to_read = String::new();
 
    io::stdin().read_line(&mut to_read).expect("Failed to read line"); 
    
    let to_read = to_read.trim_end(); // same name but new variable
 
    let contents = fs::read_to_string(to_read).expect("Something went wrong reading the file");
    
    println!("{}", contents.trim() ); 
    
}