Consumed param that can be owned or a ref in Rust

  Kiến thức lập trình

I would like to make a function that can take either owned value, or a reference that can be cloned into an owned value. This way an owned value can be passed in without extra cloning. It seems I am able to do it with a custom trait specifically for String/&str, but I couldn’t find anything similar/generic in stdlib. Am this approach incorrect?

trait MyToString {
    fn to_owned_string(self) -> String;
}

impl MyToString for &str {
    fn to_owned_string(self) -> String {
        self.to_string()
    }
}

impl MyToString for String {
    fn to_owned_string(self) -> String {
        self
    }
}

fn foo<T: MyToString>(v: T) -> String {
    v.to_owned_string()
}

fn main() {
    let s_ref: &str = "hello";
    println!("{}", foo(s_ref));

    let s_owned: String = String::from("world");
    println!("{}", foo(s_owned));
}

LEAVE A COMMENT