#owned #borrowed #cow #compile-time

maybe-owned-trait

Either an owned or borrowed value, with type known at compile time

3 unstable releases

0.2.1 Sep 14, 2023
0.2.0 Sep 14, 2023
0.1.0 Sep 14, 2023

#2691 in Rust patterns

MIT/Apache

9KB
144 lines

Either an owned or borrowed value, with type known at compile time

Crates.io Downloads Documentation License Dependency Status

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

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.

Example

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.

Dependencies

~10KB