#convert #empty #string #traits

noneifempty

将 T 转换为 None(如果为空)

4 个版本

0.1.3 2021年5月11日
0.1.2 2021年4月5日
0.1.1 2021年4月5日
0.1.0 2021年4月5日

#1651 in 文本处理


napchart 中使用

自定义许可证

7KB
64

noneifempty

GitHub last commit Crates.io Docs.rs Project Status: Active – The project has reached a stable, usable state and is being actively developed.

关于

添加了一个 NoneIfEmpty 特性,它通过将空 T 转换为 None 来将 T 转换为 Option。

用法

添加到你的 Cargo.toml

[dependencies]
noneifempty = "0.1.2"

示例

// Bring the trait into scope
use noneifempty::NoneIfEmpty;

// Converts empty strings to None
let empty_str = "";
assert_eq!(empty_str.none_if_empty(), None);

// And full strings to Some
let full_str  = "hello, world!";
assert_eq!(full_str.none_if_empty(),  Some("hello, world!"));

// Also works with vecs, hashmaps, hashsets, custom types...
let empty_vec: Vec<&str> = vec![];
let full_vec:  Vec<&str> = vec!["hi"];
assert_eq!(empty_vec.none_if_empty(), None);
assert_eq!(full_vec.none_if_empty(),  Some(vec!["hi"]));

// Automatically implemented for Option<T: NoneIfEmpty>
let no_vec:    Option<Vec<&str>>  = None;
let empty_vec: Option<Vec<&str>>  = Some(vec![]);
let full_vec:  Option<Vec<&str>>  = Some(vec!["hi"]);
assert_eq!(no_vec.none_if_empty(),    None);
assert_eq!(empty_vec.none_if_empty(), None);
assert_eq!(full_vec.none_if_empty(),  Some(vec!["hi"]));

无运行时依赖项