gpt4 book ai didi

rust - 为什么我需要使用额外的 `::` 前缀来访问导入的结构?

转载 作者:行者123 更新时间:2023-11-29 08:14:19 25 4
gpt4 key购买 nike

在我的 lib.rs 中,我想做 use std::fs::File

示例代码如下:

use std::fs::File;
use std::io::Read;

impl Css {
pub fn save_result_to_file(file_to_save: String) {
println!("Saving output to {}", file_to_save);
let mut f = File::open(file_to_save).expect("Unable to open file");
// let mut f = ::File::open(file_to_save).expect("Unable to open file"); -> Works
}
}

如果 File 之前没有 ::,我会遇到编译器错误:

|  let mut f = File::open(file_to_save).expect("Unable to open file");
| ^^^^^^^^^^ Use of undeclared type or module `File`

我的问题是 - :: 前缀是否总是必要的?我确定不是,但看不到如何执行此操作。

最佳答案

您可以将 :: 模块路径分隔符视为与文件路径中的 / 相同的方式,就像前导 /表示根目录,前导 :: 指的是应用程序的根模块。

当您使用 use 导入项目时,该项目的名称实际上成为该模块的(默认为私有(private))成员,并且可以使用绝对或相对路径从其他模块引用。所以你遇到这个问题的事实告诉我你的 use 语句在你的根模块中,而其他代码在子模块中。这就是为什么上面的评论者无法从您实际发布的代码中复制它。

你有一些像这样的模块结构:

use std::fs::File;
use std::io::Read;

mod Foo {
struct Css {}
impl Css {
pub fn save_result_to_file(file_to_save: String) {
println!("Saving output to {}", file_to_save);
let mut f = ::File::open(file_to_save).expect("Unable to open file");
}
}
}

前导 :: 是必需的,因为 File 已导入到根模块中,但您正在子模块中使用它。如果您将导入移动到包含您的代码的实际模块中,那么它可以在没有前导 :::

的情况下正常工作
mod Foo {
use std::fs::File;
use std::io::Read;

struct Css {}
impl Css {
pub fn save_result_to_file(file_to_save: String) {
println!("Saving output to {}", file_to_save);
let mut f = File::open(file_to_save).expect("Unable to open file");
}
}
}

关于rust - 为什么我需要使用额外的 `::` 前缀来访问导入的结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45786024/

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