2.5 References & Borrowing
Posted perfei
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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:
[[email protected] test]# cargo new references Created binary (application) `references` package [[email protected] test]# cd references/ [[email protected] 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() }
[[email protected] 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的主要内容,如果未能解决你的问题,请参考以下文章
php5.6 CI的问题(Only variable references should be returned by reference)
php foreach 报 “Cannot create references to elements of a temporary array expression”
Curry 2.5 SUN WUKONG & Curry 2.5 ERLANG SHEN 中国行特别版