| Crates.io | maybe-owned-trait |
| lib.rs | maybe-owned-trait |
| version | 0.2.1 |
| created_at | 2023-09-14 03:16:21.990764+00 |
| updated_at | 2023-09-14 03:35:35.7399+00 |
| description | Either an owned or borrowed value, with type known at compile time. |
| homepage | |
| repository | https://github.com/JohnScience/maybe-owned-trait |
| max_upload_size | |
| id | 972195 |
| size | 21,524 |
This crate offers a MaybeOwned trait which allows you to pass either an owned
or a borrowed value to a function. As opposed to std::borrow::Cow
and beef::Cow, this trait
Cows;However, it also creates additional mental overhead and in some cases might cause genericity-induced problems.
Eventually, definition sites might become cleaner with an attribute proc macro.
use rand::Rng;
use maybe_owned_trait::MaybeOwned;
use std::path::{Path, PathBuf};
// Definition site is a bit more verbose than with `Cow`, yet still reasonable
fn my_fn(path: impl for<'a> MaybeOwned<Owned = PathBuf, Borrowed<'a> = &'a Path>) {
// Of course, you'll have a meaningful condition here
if rand::thread_rng().gen::<bool>() {
let path_buf: PathBuf = path.to_owned();
println!("Owned buf: {:?}", path_buf);
} else {
let path: &Path = path.borrow();
println!("Borrowed path: {:?}", path);
};
}
let path = PathBuf::from("hello");
// Call sites are clean
my_fn(&path);
my_fn(path);
With beef feature enabled, this crate also provides the implementations of MaybeOwned
for beef::Cow and beef::lean::Cow.