finished ch4

This commit is contained in:
2025-01-02 14:12:46 -07:00
parent e6e5ab1a0f
commit 2e3f133c61
8 changed files with 395 additions and 4 deletions

7
ownership/Cargo.lock generated Normal file
View File

@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "ownership"
version = "0.1.0"

6
ownership/Cargo.toml Normal file
View File

@ -0,0 +1,6 @@
[package]
name = "ownership"
version = "0.1.0"
edition = "2021"
[dependencies]

34
ownership/src/main.rs Normal file
View 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
}