Crates.io | noneifempty |
lib.rs | noneifempty |
version | 0.1.3 |
source | src |
created_at | 2021-04-05 05:27:01.717248 |
updated_at | 2021-05-11 21:06:03.134076 |
description | Convert T to None if empty |
homepage | |
repository | https://github.com/barrowsys/noneifempty |
max_upload_size | |
id | 379150 |
size | 8,750 |
Adds a trait NoneIfEmpty that converts a T to an Option
Add to your 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"]));