more ch4 progress

This commit is contained in:
Rowan Torbitzky-Lane 2025-03-19 15:58:03 -05:00
parent 1b1274ff90
commit 619f32677c
4 changed files with 51 additions and 3 deletions
ch4
ownership/src
refs_and_borrow

@ -52,12 +52,16 @@ fn main() {
// When variable owns a box, when Rust deallocates the variable's frame,
// then Rust deallocates the box's heap memory.
let d = Box::new([0; 1_000_000]); // d owns this Box here
let e = d; // e has ownership of the box transfered to it from d
let e = d; // e has ownership of the box transfered to it from d. Say it's moved
// Rust data structures like String, Vec, and HashMap use Boxes.
// Stopped here for the night:
// https://rust-book.cs.brown.edu/ch04-01-what-is-ownership.html#variables-cannot-be-used-after-being-moved
// Variables can't be used after moving
// Can use .clone() to avoid moving data
let first = String::from("Ferris");
let first_clone = first.clone();
let full = add_suffix(first_clone);
println!("{full}, originally {first}");
}
fn plus_one(x: i32) -> i32 {
@ -67,3 +71,8 @@ fn plus_one(x: i32) -> i32 {
fn make_and_drop() {
let a_box = Box::new(5);
}
fn add_suffix(mut name: String) -> String {
name.push_str(" Jr. ");
name
}

7
ch4/refs_and_borrow/Cargo.lock generated Normal file

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

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

@ -0,0 +1,26 @@
fn main() {
// These lines wont work bc m1 and m2 are moved
// let m1 = String::from("Hello");
// let m2 = String::from("World");
// greet(m1, m2);
// let s = format!("{} {}", m1, m2);
// This is suboptimal
let m1 = String::from("Hello");
let m2 = String::from("World");
let (m1_again, m2_again) = greet_ret(m1, m2);
let s = format!("{} {}", m1_again, m2_again);
println!("{s}");
// stopped here:
// https://rust-book.cs.brown.edu/ch04-02-references-and-borrowing.html#references-are-non-owning-pointers
}
fn greet(g1: String, g2: String) {
println!("{} {}!", g1, g2);
}
fn greet_ret(g1: String, g2: String) -> (String, String) {
println!("{} {}!", g1, g2);
(g1, g2)
}