Created
June 5, 2017 16:21
-
-
Save anonymous/6464fd64083a1612163641dee4d5f4d7 to your computer and use it in GitHub Desktop.
Shared via Rust Playground
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#![allow(dead_code)] | |
// ※主な変更点 | |
// 1. foo(), bar() の第一引数を &self から &mut self に変更 | |
// 2. baz() を追加 | |
struct Hoge<'s> { | |
hoge: &'s str, | |
} | |
impl<'s> Hoge<'s> { | |
fn new(s: &'s str) -> Hoge<'s> { | |
Hoge { hoge: s } | |
} | |
fn display(&self) { | |
println!("{}", self.hoge) | |
} | |
// (1) &mut self, &self.hoge の lifetime が 's の場合 | |
fn foo(&'s mut self) -> &'s str { | |
self.hoge | |
} | |
// (2) &mut self, &self.hoge の lifetime をパラメータにとる場合 | |
fn bar<'f>(&'f mut self) -> &'f str { | |
self.hoge | |
} | |
// (3) &mut self の lifetime のみをパラメータにとる場合 | |
fn baz<'f>(&'f mut self) -> &'s str { | |
self.hoge | |
} | |
} | |
fn main() { | |
// (1') foo() | |
/* { | |
let s = "TEST".to_owned(); | |
let mut hoge = Hoge::new(&s); | |
let _borrow = hoge.foo(); | |
hoge.display(); | |
} */ | |
// (2') bar() | |
/* { | |
let s = "TEST".to_owned(); | |
let mut hoge = Hoge::new(&s); | |
let _borrow = hoge.bar(); | |
hoge.display(); | |
} */ | |
// (3') baz() | |
{ | |
let s = "TEST".to_owned(); | |
let mut hoge = Hoge::new(&s); | |
let _borrow = hoge.baz(); | |
hoge.display(); | |
} | |
// (1'), (2') は borrow checker により弾かれてコンパイルに失敗する | |
// ※ hoge.display() を呼び出す際,その前に読んだ時の mutable な借用が解放されていないと言われる | |
// (3') では borrow checker によるチェックをパスする | |
// ※ hoge.display() の呼び出し時には baz() で作られた &mut hoge が開放済みになる | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment