gpt4 book ai didi

rust - 如何在 Rust 中按值返回结构?

转载 作者:行者123 更新时间:2023-12-03 11:32:36 25 4
gpt4 key购买 nike

我正在学习 Rust,但第一步已经失败了……我有下一个功能:

use std::env;
use std::path::Path;

fn get_path() -> Path {
let args: Vec<String> = env::args().collect();
assert!(!args.is_empty(), "Target path is required!");
let path = Path::new(&args[0]);
assert!(path.exists(), "Target path doesn't exist!");
assert!(path.is_dir(), "Target path is not a directory!");
return path;
}

这是一个非常简单的函数,但是 path 是一个引用,我不知道如何按值从函数返回 Path 对象?或者如何返回在外部函数上下文中有效的引用?

P.S. 我寻找过类似的问题,但不幸的是我没有得到它。

最佳答案

严格来说,Path 不是一个引用,它是一个未定大小的类型,它只能存在于一个引用后面,并且确实是Path::new returns &Path not Path .因此,这与您注释函数的 -> Path 不兼容。

这些实际上是编译错误告诉你的两件事,你真的想在发布 Rust 代码时给人们编译错误(或重现案例),因为一旦你习惯了这些错误,它们就会提供非常丰富的信息:

error[E0277]: the size for values of type `[u8]` cannot be known at compilation time
--> src/lib.rs:4:18
|
4 | fn get_path() -> Path {
| ^^^^ borrow the `Path` instead
|

说你正在返回一个不允许的大小不一的类型),并且

error[E0308]: mismatched types
--> src/lib.rs:10:12
|
4 | fn get_path() -> Path {
| ---- expected `std::path::Path` because of return type
...
10 | return path;
| ^^^^ expected struct `std::path::Path`, found `&std::path::Path`

说明您要返回的类型与您要返回的值的类型不匹配。

无论如何the official documentation for Path notes , Path 的拥有/结构版本是 PathBuf ,所以你应该返回它,并将你的 Path 转换成 PathBuf,或者实际上只是首先创建一个 PathBuf,例如

use std::env;
use std::path::PathBuf;

fn get_path() -> PathBuf {
let args: Vec<String> = env::args().collect();
assert!(!args.is_empty(), "Target path is required!");
let path = PathBuf::from(&args[0]);
assert!(path.exists(), "Target path doesn't exist!");
assert!(path.is_dir(), "Target path is not a directory!");
path
}

顺便说一下,

Path::new(&args[0]);

可能不是您所期望或想要的:作为 std::env::args 的文档注释:

The first element is traditionally the path of the executable

这不是 Rust 认为适合与底层系统分离的领域。

您可能需要 args[1],或者使用更高级别的 args-parsing API。

还有一个与 Sven Marnach 对您的问题的评论相关的旁白:调用 path.exists 然后调用 path.is_dir 需要两次获取元数据(我不认为 Rust缓存此信息)。效率方面在这里可能不是最重要的,但您可能仍想显式使用 Path::metadata,然后询问 that if is_dir (Path::metadata 将返回一个 Err 如果路径不是有效的磁盘上的东西)。

关于rust - 如何在 Rust 中按值返回结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63339874/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com