首页 > Windows开发 > 详细

2.5 References & Borrowing

时间:2019-03-07 21:20:35      阅读:159      评论:0      收藏:0      [点我收藏+]

 

 

 

 

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!