我在尝试跨 Rust 中的多个文件使用自定义枚举时遇到了一个问题。我希望能够编写一个包含此枚举的文件并从多个文件中引用它(file_a.rs 运行一个返回 Shape 枚举的函数,main.rs 与类型匹配,但它需要 types::Shape 并找到一个file_a::types::Shape)。我期望的结果是两者都是 types::Shape 类型,但情况似乎并非如此。
过去,为了解决这个问题,我只是将所有产生这些冲突的代码放到同一个文件中。这似乎不是一个合适的解决方案,尤其不是专业的解决方案。
我无法找到任何文章或问题,这些文章或问题以我的方式处理在不同文件中使用枚举(如果可以的话,请指导我)。
如何在多个文件中使用枚举,同时保持所有文件的类型相同?
这是一个演示问题的小例子。错误发生在 match 语句的 main.rs 中。
目录结构:
src
| main.rs
|____core
| | types.rs
| | file_a.rs
/src/main.rs:
#[path = "./core/types.rs"]
mod types;
use types::*;
#[path = "./core/file_a.rs"]
mod file_a;
use file_a::*;
fn main()
{
match return_a_shape()
{
Shape::CIRCLE => println!("circle"), // expected enum `file_a::types::Shape`, found enum `types::Shape`
Shape::SQUARE => println!("square"), // expected enum `file_a::types::Shape`, found enum `types::Shape`
Shape::TRIANGLE => println!("triangle"), // expected enum `file_a::types::Shape`, found enum `types::Shape`
_ => println!("unknown shape"),
}
}
/src/core/file_a.rs:
mod types;
use types::*;
pub fn return_a_shape() -> Shape
{
return Shape::CIRCLE;
}
/src/types.rs:
pub enum Shape
{
SQUARE,
CIRCLE,
TRIANGLE,
}
最佳答案
我只是研究rust,但据我了解,这里的问题不在enum
, 但在 mod
.这个关键字将一个模块变成另一个模块的子模块。所以,当你制作 types
成为 file_a
的子模块和 main
,它作为两个不同的模块被导入两次。
您可以删除mod types;
来自 file_a.rs
的行并将其从父模块导入为use super::types::*;
.
use super::types::*;
pub fn return_a_shape() -> Shape
{
return Shape::CIRCLE;
}
或者您可以导入
types
模块到 file_a
但不在 main
模块,然后重新导出它:文件_a.rs
pub mod types; // Import types as a submodule and reexport it
use types::*;
pub fn return_a_shape() -> Shape
{
return Shape::CIRCLE;
}
main.rs
#[path = "./core/file_a.rs"]
mod file_a;
use file_a::*;
use file_a::types::*; // Use types submodule from the file_a module
fn main()
{
match return_a_shape()
{
Shape::CIRCLE => println!("circle"),
Shape::SQUARE => println!("square"),
Shape::TRIANGLE => println!("triangle"),
_ => println!("unknown shape"),
}
}
关于enums - 引用同一个文件时 rust 不同的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62096366/