Rust 中使用 & 获取变量的引用,这属于不可变引用,当然也有可变引用 &mut 。let y = &x 表示 y 是 x 的一个引用,x 被绑定为 5,所以断言 assert_eq!(5, x);能通过。assert_eq!(5, *y); 中 *y 表示 y 的解引用,也就是解出引用所指向的值,所以这个断言依旧能通过。然而如果 assert_eq!(5, y);.则会报错:
1 2 3 4 5 6 7 8
error[E0277]: can't compare `{integer}` with `&{integer}` --> src/main.rs:6:5 | 6 | assert_eq!(5, y); | ^^^^^^^^^^^^^^^^^ no implementation for `{integer} == &{integer}` // 无法比较整数类型和引用类型 | = help: the trait `std::cmp::PartialEq<&{integer}>` is not implemented for `{integer}`
error[E0596]: cannot borrow `*some_string` as mutable, as it is behind a `&` reference --> src/main.rs:8:5 | 7 | fnchange(some_string: &String) { | ------- help: consider changing this to be a mutable reference: `&mutString` ------- 帮助:考虑将该参数类型修改为可变的引用: `&mutString` 8 | some_string.push_str(", world"); | ^^^^^^^^^^^ `some_string` is a `&` reference, so the data it refers to cannot be borrowed as mutable `some_string`是一个`&`类型的引用,因此它指向的数据无法进行修改
error[E0499]: cannot borrow `s` as mutable more than once at a time 同一时间无法对 `s` 进行两次可变借用 --> src/main.rs:5:14 | 4 | letr1 = &mut s; | ------ first mutable borrow occurs here 首个可变引用在这里借用 5 | letr2 = &mut s; | ^^^^^^ second mutable borrow occurs here 第二个可变引用在这里借用 6 | 7 | println!("{}, {}", r1, r2); | -- first borrow later used here 第一个借用在这里使用
error[E0106]: missing lifetime specifier --> main.rs:7:16 | 7 | fndangle() -> &String { | ^ help: consider giving it a 'static lifetime: `&'static` | = help: this function'sreturntypecontains a borrowed value, but there is no value forit to be borrowed from
error: aborting due to previous error
For more information about this error, try `Rustc --explain E0106`.
1 2 3
this function'sreturntypecontains a borrowed value, but there is no value forit to be borrowed from. 该函数返回了一个借用的值,但是已经找不到它所借用值的来源
因为 s 是在 dangle 函数内创建的,当 dangle 的代码执行完毕后,s 将被释放,但是此时我们又尝试去返回它的引用。这意味着这个引用会指向一个无效的 String!
解决办法很简单,返回 s 而不是返回它的引用。
1 2 3 4 5 6 7 8 9 10
fnmain() { let_r = dangle(); // ... }
fndangle() ->String { lets = String::from("hello"); s }