enums - 引用同一个文件时 rust 不同的类型

标签 enums rust

我在尝试跨 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/

相关文章:

rust - 在 Rust 中为切片分配一个值的惯用方法是什么?

rust - 是否有单一生产者多消费者 channel 的图书馆?

c# - 如何对枚举进行空检查

android - 如何在 proguard 中保留 Enum 类型字段?

java - 如何从 Class<T> 推断 T 的方法

c - 遍历枚举值

java - 如何在 Java 中提供枚举值的实现?

rust - 类型必须满足静态生命周期

rust - 如何基于快速错误扩展错误?

rust - Rust 匹配表达式类型是不确定的吗?