2.5 References & Borrowing

Here is how you would define and use a calculate_length function that has a reference to an object as a parameter instead of taking ownership of the value:

[root@itoracle test]# cargo new references
     Created binary (application) `references` package
[root@itoracle test]# cd references/
[root@itoracle references]# vim src/main.rs 
fn main() {
    let s1 = String::from("wa ka ka ");
    let _len = get_length(&s1);
    println!("The length of '{}' is {}",s1,_len);
}

fn get_length(ss: &String) -> usize{
    ss.len()
}
[root@itoracle references]# cargo run
   Compiling references v0.1.0 (/usr/local/automng/src/rust/test/references)                                             
    Finished dev [unoptimized + debuginfo] target(s) in 7.50s                                                            
     Running `target/debug/references`
The length of 'wa ka ka ' is 9

 These ampersands are references, and they allow you to refer to some value without taking ownership of it. 

The &s1 syntax lets us create a reference that refers to the value of s1 but does not own it. Because it does not own it, the value it points to will not be dropped when the reference goes out of scope.

Likewise, the signature of the function uses & to indicate that the type of the parameter s is a reference. Let’s add some explanatory annotations:

fn get_length(s: &String) -> usize { // s is a reference to a String
    s.len()
} // Here, s goes out of scope. But because it does not have ownership of what
  // it refers to, nothing happens.

猜你喜欢

转载自www.cnblogs.com/perfei/p/10492149.html
2.5