string - 为什么从用户输入打开程序的路径时需要 .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,消息:“没有这样的文件或目录”}
为什么会这样?
解决方案
trim_end
返回 a &str
:一个切片,它是对初始字符串一部分的引用。
所以如果你这样做
to_read = to_read.trim_end()
然后您尝试将 a 分配给&str
type 的变量String
。
您采取的解决方案是String
从&str
with构建一个新的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() );
}
推荐阅读
- postgresql - 查询执行时间过长
- c# - 有没有办法在 OpenApi v3 规范属性中明确设置 nullable : false ?
- php - 自定义或 ApiPlatform 过滤嵌套资源在具有复合主键的实体中不起作用
- python - 了解 Sagemaker 对象检测预测的输出
- regex - 如何通过正则表达式从日志(splunk)中获取端口号?
- python-3.x - 如何使用 python 和 GHE API 提取文件的内容
- android - 隐藏键盘并在按钮单击时导航到新片段
- javascript - 有没有更好的方法来管理嵌套调用?
- python - 我正在尝试制作用户输入字典以获得额外的学分,但我不知道如何正确结束程序
- javascript - WKWebView 不在网页的模式窗口中显示谷歌地图