< 返回版块

shanqiang0304 发表于 2021-01-06 10:41

Tags:引用,解引用

rust中的&String 为什么不能解引用

希望能给详细解释,谢谢

评论区

写评论
zhylmzr 2021-01-17 19:28
let a = "123".to_owned();
let b = &a;
let c = *b; // error

赋值语句有两种理解,首先是Copy,没有实现Copy则move。

然后在有借用的时候,不允许move它,这是编译器规定的,否则你move了那借用指向的不是空指针了? 而String又没有实现Copy,所以无法做到解引用

ezlearning 2021-01-06 14:57

编译器自动做了哈,借用主要用于方法传参数,

这里:https://doc.rust-lang.org/book/ch05-03-method-syntax.html

Where’s the -> Operator?
In C and C++, two different operators are used for calling methods: you use . if you’re calling a method on the object directly and -> if you’re calling the method on a pointer to the object and need to dereference the pointer first. In other words, if object is a pointer, object->something() is similar to (*object).something().

Rust doesn’t have an equivalent to the -> operator; instead, Rust has a feature called automatic referencing and dereferencing. Calling methods is one of the few places in Rust that has this behavior.

Here’s how it works: when you call a method with object.something(), Rust automatically adds in &, &mut, or * so object matches the signature of the method. In other words, the following are the same:
1 共 2 条评论, 1 页