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

如何在Rust文档测试中正确引入函数?编译报错求解

解决Rust文档测试的unresolved import错误

错误原因分析

你遇到的E0432错误核心有两点:

  1. 函数未公开:文档测试默认以外部 crate 的视角执行,非公开(未加pub)的函数无法被外部导入访问。
  2. 导入路径不完整:如果函数位于子模块中,crate::开头的路径缺少完整模块层级,导致找不到目标函数。

修复步骤

1. 标记函数为公开

给目标函数添加pub修饰符,确保外部上下文(包括文档测试)可以访问它:

/// Given an axis in 3D returns the indices of the 3 basis axis in the order such
/// that the first index represents forward (the input) the next the side and the final
/// the up. i.e. it computes the even permutation of basis index that creates the
/// rotation that aligns the basis with the selected axis.
///
/// # Arguments
///
/// * index an index from 0-2 selecting the forward axis.
///
/// # Examples
///
/// ```
/// use crate::axis_index_to_basis_indices;
/// let x_index = 0;
/// let y_index = 1;
/// let z_index = 2;
/// let (forward, side, up) = axis_index_to_basis_indices(x_index);
/// assert!(forward == x_index);
/// assert!(side == y_index);
/// assert!(up == z_index);
///
/// let (forward, side, up) = axis_index_to_basis_indices(z_index);
/// assert!(forward == z_index);
/// assert!(side == x_index);
/// assert!(up == y_index);
/// ```
pub fn axis_index_to_basis_indices(index: i32) -> (i32, i32, i32)
{
    match index
    {
        0 => (0, 1, 2),
        1 => (1, 2, 0),
        2 => (2, 0, 1),
        _ => panic!(),
    }
}

2. 修正导入路径(如果函数在子模块)

如果你的函数位于dual_contouring.rs子模块中,先在lib.rs里声明该模块:

// lib.rs
pub mod dual_contouring;

然后更新文档测试中的导入路径,补充完整模块层级:

/// # Examples
///
/// ```
/// use crate::dual_contouring::axis_index_to_basis_indices;
/// // 测试代码保持不变
/// ```

额外说明

如果不需要将函数对外公开(仅内部测试用),可以在文档测试中使用相对路径super::axis_index_to_basis_indices,但这种方式仅适用于函数和测试在同一模块的场景,且不符合文档测试验证公开接口的设计初衷。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 07:25:34