Skip to content

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

License

Apache-2.0, MIT licenses found

Licenses found

Apache-2.0
LICENSE-APACHE
MIT
LICENSE-MIT
Notifications You must be signed in to change notification settings

JohnScience/maybe-owned-trait

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

8 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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.

About

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

Resources

License

Apache-2.0, MIT licenses found

Licenses found

Apache-2.0
LICENSE-APACHE
MIT
LICENSE-MIT

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages