-
-
Save ircnelson/e21893db90eba1e2c48b7531a0865c78 to your computer and use it in GitHub Desktop.
Rust Playground (Lifetime examples)
This file contains 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
pub struct TextEditor { | |
text: String //Private member variable | |
} | |
impl TextEditor { | |
pub fn new() -> TextEditor { | |
TextEditor{text: String::new()} | |
} | |
pub fn add_char(&mut self, ch : char) { | |
self.text.push(ch); | |
} | |
// Clona o valor em uma nova área de memória. Essa solução é muito cara. | |
/**/ | |
pub fn get_text_clone(&self) -> String { | |
self.text.clone() | |
} | |
// Rust não vai deixar. | |
// Esse código implacaria em mudança de ownership causando um provável 'Double free'. | |
/* | |
pub fn get_text_copy(&self) -> String { | |
return self.text | |
} | |
*/ | |
pub fn get_text(&self) -> &String { | |
return &self.text; | |
} | |
/* Beghind the scenes... | |
pub fn get_text<'a>(&'a self) -> &'a String { | |
return &self.text; | |
} | |
*/ | |
pub fn reset(&mut self) { | |
self.text = String::new(); | |
} | |
} | |
fn main() { | |
use_after_free_example(); | |
} | |
/* | |
fn good() { | |
let mut editor = TextEditor::new(); | |
editor.add_char('a'); | |
editor.add_char('b'); | |
editor.add_char('c'); | |
/* With clone | |
let my_txt = editor.get_text_clone(); | |
*/ | |
/* With borrow */ | |
let my_txt = editor.get_text(); | |
println!("{}", my_txt); | |
} | |
fn trouble_in_compile_time() { | |
let my_txt; | |
{ | |
let mut editor = TextEditor::new(); | |
editor.add_char('a'); | |
editor.add_char('b'); | |
editor.add_char('c'); | |
my_txt = editor.get_text(); | |
} //Variable 'editor' destroyed. | |
println!("{}", my_txt); //Use after free. Not possible. | |
} | |
*/ | |
fn use_after_free_example() { | |
let mut editor = TextEditor::new(); | |
editor.add_char('a'); | |
editor.add_char('b'); | |
editor.add_char('c'); | |
let my_txt = editor.get_text(); | |
editor.reset(); | |
reader(&my_txt); //Use after free. Not possible. | |
} | |
fn reader(text : &String) { | |
println!("{}", text); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment