码迷,mamicode.com
首页 > Windows程序 > 详细

2.5 References & Borrowing

时间:2019-03-07 20:48:17      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:out   type   main   style   rop   color   http   ram   debuginfo   

 

 

 

 

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.

 

2.5 References & Borrowing

标签:out   type   main   style   rop   color   http   ram   debuginfo   

原文地址:https://www.cnblogs.com/perfei/p/10492149.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!