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

开发Rust OTF解码库时lib.rs无法引用同目录reader.rs怎么办

问题原因与修复方案

核心错误根源

你遇到的编译错误完全来自src/main.rs里错误的模块声明:mod lib;,该声明触发了Rust模块解析规则的连锁错误:

  • Rust包中lib.rs是库 crate 的根文件,main.rs是二进制 crate 的根文件,二者是同包下平级的两个独立入口,不存在从属关系。
  • 你在main.rs中写mod lib;相当于主动告诉编译器:lib是当前二进制 crate 的子模块,需要从src/lib.rs或src/lib/mod.rs加载。这时候编译器就会把原本作为库根的lib.rs当成main的子模块处理。
  • 此时lib.rs里声明的mod reader;会被编译器判定为子模块的子模块,需要放在src/lib/reader.rs路径下,和你实际的src/reader.rs路径不符,所以抛出file not found for module 'reader'错误。
  • 第二个could not find 'OpenTypeFontReader' in 'reader'错误是第一个错误的连锁反应:reader模块本身加载失败,自然找不到内部的结构体。

修复步骤

只需要修改src/main.rs即可,不需要调整其他文件的位置和代码:

  1. 删除mod lib;这行声明
  2. 调用库的decode方法时,直接用包名otfdecode作为前缀引用(Cargo会自动把同包下的库 crate 注入到二进制的依赖中)

修复后的src/main.rs完整代码:

//! OTFDecode - A CLI application to verify that the `OTFDecode` library is correctly implemented.

/// Represents the `main` entry point for the application.
/// This function is executed when the application is started.
fn main() {
    let data: [u8; 6] = [
        // OTF Header.
        /* - SFNT Version.     */ 0x00, 0x01, 0x00, 0x00,
        /* - Number of tables. */ 0x00, 0x19,
    ];

    let decoded_otf = otfdecode::decode(&data);

    println!("OTF Font inspection.");
    println!("- SFNT Version: {:?}", decoded_otf.sfnt_version);
    println!("- Number of tables: {:?}", decoded_otf.num_tables);
}

注:顺便修正了原代码中打印字段的文案错误,把Number of:改为了语义更清晰的Number of tables:

修改完成后重新执行cargo run即可正常编译运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 07:36:04