fn is_hello<T: AsRef<str>>(s: T) {
assert_eq!("hello", s.as_ref());
}
let s = "hello";
is_hello(s);
let s = "hello".to_string();
is_hello(s);
其中我对AsRef<str>
的理解是 它需要传入参数 s 要是一个字符串引用,而 string &str
都可以转成字符串引用,所以它可以传入?
不知道这个理解有什么错
fn is_hello<T: AsRef<str>>(s: T) {
assert_eq!("hello", s.as_ref());
}
let s = "hello";
is_hello(s);
let s = "hello".to_string();
is_hello(s);
其中我对AsRef<str>
的理解是 它需要传入参数 s 要是一个字符串引用,而 string &str
都可以转成字符串引用,所以它可以传入?
不知道这个理解有什么错
AsRef
AsRef<T>
是一个 trait 。T: AsRef<str>
表示 T 是一个实现了AsRef<str>
这个 trait 的类型。str
跟String
都实现了AsRef<str>
。