How to accept &str, String and &String in a single function?

前端 未结 1 1832
难免孤独
难免孤独 2021-02-07 09:12

I want to write a single function, that accepts a &str, a String and a borrowed &String. I\'ve written the following 2 functions:<

相关标签:
1条回答
  • 2021-02-07 09:29

    You can use the AsRef<str> trait:

    // will accept any object that implements AsRef<str>
    fn print<S: AsRef<str>>(stringlike: S) {
        // call as_ref() to get a &str
        let str_ref = stringlike.as_ref();
    
        println!("got: {:?}", str_ref)
    }
    
    fn main() {
        let a: &str = "str";
        let b: String = String::from("String");
        let c: &String = &b;
    
        print(a);
        print(c);
        print(b);
    }
    

    The print function will support any type that implements AsRef<str>, which includes &str, String and &String.

    0 讨论(0)
提交回复
热议问题