#private #proc-macro #features #macro

internal

Rust 中的内部字段

3 个版本

0.1.4 2024 年 1 月 13 日
0.1.3 2024 年 1 月 13 日
0.1.2 2024 年 1 月 13 日

25#private

MIT 许可证

12KB
248

internal

私有字段是一个错误。

什么意思?

好吧,可能有点夸张。

私有字段并不坏;它们有用途

  1. 允许库开发者在不进行主要 semver 跳跃的情况下对事物进行破坏性更改。
  2. 防止消费者意外导致 UB。
  3. 启用编译器优化。

但有一种更好的方法。

私有字段的主要问题在于,嗯,它使事物变得私有。将潜在有用的功能锁起来太容易了。

解决这个问题的一种方法是内部字段,但 Rust 没有这个功能。这个包通过进程宏和功能标志将此功能引入 Rust。

内部字段是如何工作的?

默认情况下,内部字段无法访问,但可以在绝对必要时启用和使用。

这是对库开发和库使用自由的平衡解决方案。可以轻松地知道什么可能会改变,但没有人受限或负担。更重要的是,当内部字段不被访问时,编译器仍然可以利用性能改进。

internal 包通过仅在库启用 "internal" 功能时公开字段来实现“Rust 方式”。它还将在所有内部字段的顶部添加文档注释警告,以清楚地说明何时有什么是内部的。

使用方法

cargo add internal

要标记某个内容为内部,请使用 internal 进程宏。它有效地替换了私有字段,因为当存在内部字段时,它们是无用的。

该宏递归地标记其下的所有私有内容为内部。因此,如果您定义 #[internal] mod stuff {...},则 stuff 内部及其包含的所有私有内容将变为内部。如果您将 stuff 公开,它本身将始终公开,但仍会递归地应用内部。

your_lib

use internal::internal;

#[internal]
fn internal_fn(arg: InternalStruct) {
	// ...
}

#[internal]
#[derive(Clone)]
struct InternalStruct {
	field: PrivateThing
}

#[internal]
mod internal_mod {
   pub struct PublicStruct {
      internal_field: PublicThing
   }
}

consumer

# Cargo.toml

your_lib = { features = ["internal"] }
// mod.rs

// If the `internal` feature is explicitly enabled,
// anything marked as internal will become public.
use your_lib::{internal_fn, InternalStruct, internal_mod};

internal_fn(InternalStruct {
	field: ...
});

// Everything gets publicized recursively.
private_mod::PublicStruct {
	internal_field: ...
}

依赖关系

~265–720KB
~17K SLoC