#非空 #字符串 #str #非零

非空字符串

一个简单的非空字符串类型,类似于 NonZeroUsize 及其相关类型

6 个版本

0.2.4 2023 年 10 月 3 日
0.2.3 2022 年 11 月 27 日
0.2.2 2022 年 9 月 18 日
0.1.0 2021 年 9 月 25 日

#925解析器实现

Download history 2129/week @ 2024-03-13 2986/week @ 2024-03-20 2083/week @ 2024-03-27 2064/week @ 2024-04-03 2085/week @ 2024-04-10 3776/week @ 2024-04-17 4055/week @ 2024-04-24 3384/week @ 2024-05-01 3026/week @ 2024-05-08 3672/week @ 2024-05-15 2341/week @ 2024-05-22 3453/week @ 2024-05-29 2239/week @ 2024-06-05 1745/week @ 2024-06-12 1195/week @ 2024-06-19 1738/week @ 2024-06-26

7,509 次下载/月

MIT/Apache 协议

21KB
380

非空字符串

Crates.io Documentation

一个简单包装类型,确保字符串内部不为空,类似于 String

示例

use non_empty_string::NonEmptyString;

// Constructing it from a normal (non-zero-length) String works fine.
let s = "A string with a length".to_owned();
assert!(NonEmptyString::new(s).is_ok());

// But constructing it from a zero-length String results in an `Err`, where we get the `String` back that we passed in.
let empty = "".to_owned();
let result = NonEmptyString::new(empty);
assert!(result.is_err());
assert_eq!(result.unwrap_err(), "".to_owned())

std::string::String 的方法

NonEmptyString 实现了类似于 String 的一些函数,只是将其转发到基础字符串,允许使用索引范围等操作

如果缺少实现 NonEmptyString 约束的函数特性,请不要犹豫,在 GitHub 仓库 issues 中提出问题。

如果缺少实现 NonEmptyString 约束的函数特性,请不要犹豫,在 GitHub 仓库 issues 中提出问题。

特质

NonEmptyString 实现了类似于 String 的一些特质,其中简单地将它转发到基础字符串,允许使用索引范围等操作

use non_empty_string::NonEmptyString;

let non_empty = NonEmptyString::new("ABC".to_owned()).unwrap();
assert_eq!(&non_empty[1..], "BC");

如果缺少实现 NonEmptyString 约束的特质,请不要犹豫,在 GitHub 仓库 issues 中提出问题。

序列化支持

serde 支持可通过 serde 功能标志使用

[dependencies]
serde = { version = "1", features = ["derive"] }
non-empty-string = { version = "*", features = ["serde"]}

之后可以在结构体中使用它

use serde::{Serialize, Deserialize};
use non_empty_string::NonEmptyString;

#[derive(Serialize, Deserialize)]
struct MyApiObject {
  username: NonEmptyString,
}

如果字段作为一个字符串存在,序列化将失败,但字符串的长度为 0。

许可

许可协议:Apache 许可协议 2.0 (LICENSE-APACHEhttps://apache.ac.cn/licenses/LICENSE-2.0)

贡献

贡献者:```

除非您明确表示,否则您根据Apache-2.0许可证定义的,有意提交以包含在作品中的任何贡献,应按上述方式双授权,不得添加任何额外条款或条件。

依赖项

~1.5MB
~36K SLoC