let s = String::from("hello world");
let len = s.len();
let len = &s.len();
fn cal_len(s:&String) -> usize { s.len() }
String 的len函数签名是 pub fn len(&self) -> usize;
为什么我既可以对s调用len函数,也可以对s的引用调用len函数,而且结果都是正确的
1
共 3 条评论, 1 页
评论区
写评论感谢回复 对以下内容的回复:
对以下内容的回复:
对,这个是deref coercion,参见The Book: https://doc.rust-lang.org/book/ch15-02-deref.html?highlight=coercion#implicit-deref-coercions-with-functions-and-methods
因为Rust对 . 运算符自动做了 * 引用,并且这个解引用的次数是编译器自动计算出来的(比人工厉害)。比如,你写 &&&&&&&&&&&String,一样是可以的。
:D