References and Borrowing

1. References

Ownership 中的最后一個(gè)例子,我們?nèi)绻胍俅文没貍魅氲膶?duì)象的話意鲸,就得返回出來(lái),這種做法有點(diǎn)繁瑣做粤,為此Rust提供了一個(gè)references類(lèi)型

有點(diǎn)像指針,但是一定可以保證其對(duì)應(yīng)的值是一個(gè)valid的

fn main() {
    let s1 = String::from("hello");

    let len = calculate_length(&s1);

    println!("The length of '{}' is {}.", s1, len);
}

fn calculate_length(s: &String) -> usize {
    s.len()
}

參數(shù)內(nèi)容如下圖所示:

圖片.png

用ownership來(lái)解釋如下:

&s1創(chuàng)建了一個(gè)reference來(lái)引用s1捉撮,但是這個(gè)reference并不擁有它,則reference指向的值在該reference離開(kāi)作用域的時(shí)候怕品,并不會(huì)drop掉

fn calculate_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, it is not dropped.

1.1 Borrowing

We call the action of creating a reference borrowing

As in real life, if a person owns something, you can borrow it from them. When you’re done, you have to give it back. You don’t own it

1.2 Borrowing戒律

Borrowing得到的引用默認(rèn)是不可變的

fn main() {
    let s = String::from("hello");

    change(&s);
}

fn change(some_string: &String) {
    some_string.push_str(", world");
}
$ cargo run
   Compiling ownership v0.1.0 (file:///projects/ownership)
error[E0596]: cannot borrow `*some_string` as mutable, as it is behind a `&` reference
 --> src/main.rs:8:5
  |
7 | fn change(some_string: &String) {
  |                        ------- help: consider changing this to be a mutable reference: `&mut String`
8 |     some_string.push_str(", world");
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `some_string` is a `&` reference, so the data it refers to cannot be borrowed as mutable

For more information about this error, try `rustc --explain E0596`.
error: could not compile `ownership` due to previous error

1.3 Mutable References

上述代碼,可以采用Mutable References來(lái)解決

fn main() {
    let mut s = String::from("hello");

    change(&mut s);
}

fn change(some_string: &mut String) {
    some_string.push_str(", world");
}

1.3.1 Mutable References具有唯一性巾遭,避免多個(gè)寫(xiě)操作

fn main() {
    let mut s = String::from("hello");

    let r1 = &mut s;
    let r2 = &mut s;

    println!("{}, {}", r1, r2);
}
$ cargo run
   Compiling ownership v0.1.0 (file:///projects/ownership)
error[E0499]: cannot borrow `s` as mutable more than once at a time
 --> src/main.rs:5:14
  |
4 |     let r1 = &mut s;
  |              ------ first mutable borrow occurs here
5 |     let r2 = &mut s;
  |              ^^^^^^ second mutable borrow occurs here
6 | 
7 |     println!("{}, {}", r1, r2);
  |                        -- first borrow later used here

For more information about this error, try `rustc --explain E0499`.
error: could not compile `ownership` due to previous error

1.3.2 多個(gè)Mutable References采用不同作用域

fn main() {
    let mut s = String::from("hello");

    {
        let r1 = &mut s;
    } // r1 goes out of scope here, so we can make a new reference with no problems.

    let r2 = &mut s;
}

1.3.3 Mutable References和Immutable References混用

fn main() {
    let mut s = String::from("hello");

    let r1 = &s; // no problem
    let r2 = &s; // no problem
    let r3 = &mut s; // BIG PROBLEM

    println!("{}, {}, and {}", r1, r2, r3);
}

可以采用作用域的方式繞過(guò)去

fn main() {
    let mut s = String::from("hello");

    let r1 = &s; // no problem
    let r2 = &s; // no problem
    println!("{} and {}", r1, r2);
    // variables r1 and r2 will not be used after this point

    let r3 = &mut s; // no problem
    println!("{}", r3);
}

1.4 Dangling References

fn main() {
    let reference_to_nothing = dangle();
}

fn dangle() -> &String {
    let s = String::from("hello");

    &s
}

上述代碼報(bào)錯(cuò)如下:

$ cargo run
   Compiling ownership v0.1.0 (file:///projects/ownership)
error[E0106]: missing lifetime specifier
 --> src/main.rs:5:16
  |
5 | fn dangle() -> &String {
  |                ^ expected named lifetime parameter
  |
  = help: this function's return type contains a borrowed value, but there is no value for it to be borrowed from
help: consider using the `'static` lifetime
  |
5 | fn dangle() -> &'static String {
  |                ~~~~~~~~

For more information about this error, try `rustc --explain E0106`.
error: could not compile `ownership` due to previous error

可以看到:

this function's return type contains a borrowed value, but there is no value for it to be borrowed from

上述代碼詳細(xì)注釋如下:

fn main() {
    let reference_to_nothing = dangle();
}

fn dangle() -> &String { // dangle returns a reference to a String

    let s = String::from("hello"); // s is a new String

    &s // we return a reference to the String, s
} // Here, s goes out of scope, and is dropped. Its memory goes away.
  // Danger!

s對(duì)象離開(kāi)了作用域之后會(huì)被drop掉肉康,而引用也自然就沒(méi)用了

一種簡(jiǎn)單的解決方法是直接返回對(duì)象:

fn main() {
    let string = no_dangle();
}

fn no_dangle() -> String {
    let s = String::from("hello");

    s
}

Ref:

  1. https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市灼舍,隨后出現(xiàn)的幾起案子吼和,更是在濱河造成了極大的恐慌,老刑警劉巖骑素,帶你破解...
    沈念sama閱讀 218,122評(píng)論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件炫乓,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡献丑,警方通過(guò)查閱死者的電腦和手機(jī)蹄皱,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,070評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門(mén)屡贺,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人,你說(shuō)我怎么就攤上這事婉宰》档” “怎么了鸦泳?”我有些...
    開(kāi)封第一講書(shū)人閱讀 164,491評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵岔乔,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我咖熟,道長(zhǎng)圃酵,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,636評(píng)論 1 293
  • 正文 為了忘掉前任馍管,我火速辦了婚禮郭赐,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘确沸。我一直安慰自己捌锭,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,676評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布罗捎。 她就那樣靜靜地躺著观谦,像睡著了一般。 火紅的嫁衣襯著肌膚如雪桨菜。 梳的紋絲不亂的頭發(fā)上豁状,一...
    開(kāi)封第一講書(shū)人閱讀 51,541評(píng)論 1 305
  • 那天捉偏,我揣著相機(jī)與錄音,去河邊找鬼泻红。 笑死夭禽,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的谊路。 我是一名探鬼主播讹躯,決...
    沈念sama閱讀 40,292評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼缠劝!你這毒婦竟也來(lái)了潮梯?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 39,211評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤惨恭,失蹤者是張志新(化名)和其女友劉穎酷麦,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體喉恋,經(jīng)...
    沈念sama閱讀 45,655評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,846評(píng)論 3 336
  • 正文 我和宋清朗相戀三年母廷,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了轻黑。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,965評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡琴昆,死狀恐怖氓鄙,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情业舍,我是刑警寧澤抖拦,帶...
    沈念sama閱讀 35,684評(píng)論 5 347
  • 正文 年R本政府宣布,位于F島的核電站舷暮,受9級(jí)特大地震影響态罪,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜下面,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,295評(píng)論 3 329
  • 文/蒙蒙 一复颈、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧沥割,春花似錦耗啦、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,894評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至椒拗,卻和暖如春似将,著一層夾襖步出監(jiān)牢的瞬間获黔,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,012評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工玩郊, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留肢执,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,126評(píng)論 3 370
  • 正文 我出身青樓译红,卻偏偏與公主長(zhǎng)得像预茄,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子侦厚,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,914評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容