mirror of
https://github.com/darkicewolf50/RustBrock.git
synced 2025-08-03 08:40:54 -06:00
finished ch4
This commit is contained in:
34
ownership/src/main.rs
Normal file
34
ownership/src/main.rs
Normal file
@ -0,0 +1,34 @@
|
||||
use std::char;
|
||||
|
||||
fn main() {
|
||||
println!("Hello, world!");
|
||||
// ownership_ex();
|
||||
borrowing_references();
|
||||
}
|
||||
|
||||
|
||||
fn ownership_transfer_ex () {
|
||||
// this is a string literal
|
||||
let s = "hello";
|
||||
// this is a string
|
||||
let ab = String::from("hello");
|
||||
let a: char = ab.chars().nth(0).expect("REASON");
|
||||
println!("{}", a); // outputs 'h'
|
||||
|
||||
// do stuff with s
|
||||
}
|
||||
// is is out of scope and therefore invalid
|
||||
|
||||
fn borrowing_references () {
|
||||
let mut s1 = String::from("hello");
|
||||
change_string(&mut s1);
|
||||
// s1 is still valid aat this point so ownership didint change
|
||||
println!("{}", s1);
|
||||
// do more stuff with s1
|
||||
}
|
||||
|
||||
fn change_string (some_string: &mut String) {
|
||||
// using borrowed value contained in some_string
|
||||
some_string.push_str(", world");
|
||||
// some_string out of scope and therefore invalid
|
||||
}
|
Reference in New Issue
Block a user