【问题标题】:Invalid UTF-8 Stream on mod importmod 导入时 UTF-8 流无效
【发布时间】:2022-01-09 06:15:34
【问题描述】:

主要问题

如何在main.rs 中使用来自helper1.rs 的代码。

// main.rs
mod lib;
use lib::lib_function;
use lib::public_library;

mod module_a;
mod module_b;
use module_a::{helper1::helper1_function, mod_a_function};
use module_b::{helper2, helper3, mod_b_function};

fn main() {
    println!("Hello, world from main!");
    lib_function();
    public_library::public_library_mod_function();

    helper1_function();
    mod_a_function();

    helper2::helper2_function();
    helper3::helper3_function();
    mod_b_function();
}

// module_b/mod.rs
pub mod helper2;
pub mod helper3;

pub fn mod_a_function() {
    println!("Printing from module_b/mod.rs");
}


// module_b/helper2.rs
pub fn helper2_function() {
    println!("Hello from Helper 2!!");
}

我得到错误:

error: couldn't read src\module_b\mod.rs: stream did not contain valid UTF-8
  --> src\main.rs:14:1
   |
14 | mod module_b;
   | ^^^^^^^^^^^^^

error: could not compile `rust_modules_cheat_sheet` due to previous error

我不确定module_b 中有哪些非utf-8 字符,但module_a 中没有。

Rust 中的模块和导入备忘单

我在网上看到很多教程都说同样的话,但对于其他情况来说并不完整或复杂。我想询问社区以及研究如何在 rust 中使用来自各种情况和模块的代码。如果您想在下面对我现在不确定的两种情况发表评论,我们将不胜感激。

示例目录

/src
| main.rs
| lib.rs
| other.rs
|- module_a/
| | mod.rs
| | helper1.rs
|- module_b/
| | mod.rs
| | helper2.rs
| | helper3.rs

各种情况

  • main.rs 中使用来自other.rs 的代码(已了解)
  • main.rs 中使用来自lib.rs 的代码(已了解)
  • lib.rs 中使用来自mod.rs 的代码(已了解)
  • main.rs 中使用来自helper1.rs 的代码(已了解)
  • helper3.rs 中使用来自helper2.rs 的代码(不确定)
  • module_b/mod.rs 中使用来自module_a/mod.rs 的代码(使用 crate::module_a)

Github 存储库供将来参考

Link to repo 希望这对将来的其他人有所帮助。我知道我需要它。

谢谢

【问题讨论】:

  • 请编辑您的问题以提出有关一段代码的具体问题,该问题应包含在问题中。
  • 这似乎不是您要问的,但请注意 mod lib; 不正确 - lib.rs 是库 crate 的 crate 根,从二进制文件中它应该是由 Cargo.toml 中声明的包名引用(例如use rust_modules_cheat_sheet::lib_function;),而不是mod。使用mod 意味着在两个上下文中编译代码两次,这会导致重复的警告/错误和其他问题。
  • 这么说是有道理的,但是当有 main.rs 和 lib.rs 时,这意味着什么?那还是图书馆风格的箱子吗?是否应该在 lib.rs 中完成所有 mod 的使用,以便将所有二进制文件都拉入 lib.rs 的范围? @kevin-reid
  • @Lacrosse343 如果存在lib.rsmain.rs,那么Cargo 将从lib.rs 编译一个库包main.rs 编译一个二进制包。二进制文件可能来自库中的use 项。

标签: rust import module


【解决方案1】:

这并不是对 Rust 模块系统的误解。您的 module_b\mod.rs 文件是 UTF-16 编码的,而不是 Rust 所期望的 UTF-8 编码。

如果您使用的是 VS Code:Change the encoding of a file in Visual Studio Code 您可以通过单击底部状态栏的UTF-16 LE 部分并选择Save with encoding,然后选择UTF-8 来更改编码。

如果使用 Vim:How can I change a file's encoding with vim?

【讨论】:

  • 谢谢,很容易解决。我在 VS 中创建了整个目录,所以我想知道是什么键或操作使我的 3 个文件编码为 UTF-16 LE 而其他文件编码为 UTF8。
猜你喜欢
  • 2013-06-13
  • 2016-01-08
  • 1970-01-01
  • 1970-01-01
  • 2011-05-29
  • 2020-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多