Crate into_owned[][src]

Expand description

Provides a way to efficiently get an owned value of a type.

use into_owned::{IntoOwned, Owned};

fn check<S: IntoOwned<str>>(s: S) -> String {
    s.into_owned()
}

let _foo = check("foo"); // will clone
let _bar = check(Owned("bar".to_owned())); // will not clone twice (unlike regular ToOwned)
use into_owned::{IntoOwned, Owned};

/// A simple type that increments an internal counter on clone
pub struct Counter(usize);
impl Clone for Counter {
    fn clone(&self) -> Self {
        Self(self.0 + 1)
    }
}

fn check<S: IntoOwned<Counter>>(s: S) -> Counter {
    s.into_owned()
}

let count = check(&Counter(0)); // pass by ref
assert_eq!(count.0, 1); // counter was cloned.

let count = check(Owned(Counter(0))); // pass by value
assert_eq!(count.0, 0); // counter was not cloned.

let count = check(Cow::Borrowed(&Counter(0))); // pass by ref (Cow)
assert_eq!(count.0, 1); // counter was cloned.

let count = check(Cow::Owned(Counter(0))); // pass by value (Cow)
assert_eq!(count.0, 0); // counter was not cloned.

Structs

Due to implementation conflicts, IntoOwned cannot be directly implemented on T. So instead, this is a light wrapper that allows the implementation.

Traits

Extension to ToOwned. Avoiding clones where possible