You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rust如何在tests模块内访问外部定义的Example结构体?

如何在"tests"模块内部访问外部定义的"Example"?

src/main.rs 的初始代码:

struct Example {}

#[cfg(test)]
mod tests {
    #[test]
    fn example() {
        // Example 不在当前作用域内
    }
}

当前 Example 处于 tests 模块的作用域之外,无法直接访问。

解决方法如下:

  • 方法一:使用 super 关键字直接访问
    通过 super:: 引用父作用域的项:

    struct Example {}
    
    #[cfg(test)]
    mod tests {
        #[test]
        fn example() {
            let _ = super::Example {};
        }
    }
    
  • 方法二:用 use 语句引入作用域
    在 tests 模块内引入外部项,之后可直接使用:

    struct Example {}
    
    #[cfg(test)]
    mod tests {
        use super::Example;
    
        #[test]
        fn example() {
            let _ = Example {};
        }
    }
    
  • 方法三:使用 crate 关键字从根访问
    若 Example 定义在 crate 根,可通过 crate:: 直接访问:

    struct Example {}
    
    #[cfg(test)]
    mod tests {
        #[test]
        fn example() {
            let _ = crate::Example {};
        }
    }
    

内容的提问来源于stack exchange,提问作者Test

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 19:20:32