首页 > 解决方案 > 为什么从用户输入打开程序的路径时需要 .to_string() 方法?

问题描述

以下代码打开一个文件:

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() ); 
    
}

根据我所读到的,.to_string()它将给定值转换为字符串。让我感到困惑的是,在我的代码中,给定的值,即分配给变量的值to_read在其赋值时已经是一个字符串:let mut to_read = String::new();。我通过修补发现,该行to_read = to_read.trim_end().to_string();是我的代码工作所必需的,否则 Rust 会因以下消息而恐慌:

'读取文件出错:Os { 代码:2,种类:NotFound,消息:“没有这样的文件或目录”}

为什么会这样?

标签: stringrustuser-input

解决方案


trim_end返回 a &str:一个切片,它是对初始字符串一部分的引用。

所以如果你这样做

to_read = to_read.trim_end()

然后您尝试将 a 分配给&strtype 的变量String

您采取的解决方案是String&strwith构建一个新的to_string()。虽然这行得通,但它是无用的昂贵,因为您在read_to_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() ); 
    
}

推荐阅读