Crates.io | ext-trait |
lib.rs | ext-trait |
version | 2.0.0 |
source | src |
created_at | 2021-10-23 15:43:11.985095 |
updated_at | 2024-07-11 11:50:03.980164 |
description | Annotation to easily define ad-hoc / one-shot extension traits |
homepage | |
repository | https://github.com/danielhenrymantilla/ext-trait.rs |
max_upload_size | |
id | 469949 |
size | 26,394 |
::ext-trait
Also
#[macro_use]
extern crate ext_trait;
#[extension(trait Also)]
impl<T> T {
fn also (mut self, f: impl FnOnce(&mut Self))
-> Self
{
f(&mut self);
self
}
}
fn main ()
{
use ::std::{collections::HashMap, ops::Not};
let /* immut */ map = HashMap::with_capacity(2).also(|m| {
m.insert("foo", 42);
m.insert("bar", 27);
});
assert!(map.contains_key("foo"));
assert!(map.contains_key("bar"));
assert!(map.contains_key("baz").not());
}
WithPath
#[macro_use]
extern crate ext_trait;
use ::std::{error::Error, path::{Path, PathBuf}};
#[extension(trait WithPath)]
impl PathBuf {
fn with (mut self, segment: impl AsRef<Path>)
-> PathBuf
{
self.push(segment);
self
}
}
fn main ()
-> Result<(), Box<dyn Error>>
{
let some_dir = PathBuf::from(::std::env::var("MY_LIB_SOME_DIR")?);
// Contrary to chaining `.join()`, this reuses the memory!
let some_subdir = some_dir.with("some").with("sub").with("dir");
// …
Ok(())
}
Context
#[macro_use]
extern crate ext_trait;
use ::std::{error::Error, fmt::Display};
#[extension(trait Context)]
impl<Ok, Err : Display> Result<Ok, Err> {
fn context (self, prefix: impl Display)
-> Result<Ok, String>
{
self.map_err(|err| format!("{}: {}", prefix, err))
}
}
fn main ()
-> Result<(), Box<dyn Error>>
{
let file_contents =
::std::fs::read_to_string("some/file")
.context("Error when opening some/file")?
;
// …
Ok(())
}
Similar to https://docs.rs/extension-trait, but for the following:
Supports generics (see Context
)
search/grep 'trait TraitName'
-friendly!