{"id":16852633,"url":"https://github.com/deckarep/rust-notes","last_synced_at":"2026-02-23T00:08:56.149Z","repository":{"id":146669132,"uuid":"56021572","full_name":"deckarep/rust-notes","owner":"deckarep","description":"A place for my rust notes","archived":false,"fork":false,"pushed_at":"2016-05-06T04:03:16.000Z","size":10,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-01-24T16:35:57.858Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/deckarep.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2016-04-12T01:44:08.000Z","updated_at":"2016-04-12T01:44:08.000Z","dependencies_parsed_at":"2023-04-12T23:47:37.089Z","dependency_job_id":null,"html_url":"https://github.com/deckarep/rust-notes","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/deckarep%2Frust-notes","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/deckarep%2Frust-notes/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/deckarep%2Frust-notes/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/deckarep%2Frust-notes/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/deckarep","download_url":"https://codeload.github.com/deckarep/rust-notes/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":244198395,"owners_count":20414443,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-10-13T13:48:07.129Z","updated_at":"2025-10-25T11:52:54.596Z","avatar_url":"https://github.com/deckarep.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# rust-notes\nA place for my rust notes. This is a repo that I'll be building out to aggregate my adventure with learning rust.  It will contain my own content as well as content from others and all Copyright Claim is held accordingly by each original author's works.\n\n## [Intro to Rust - Alex Crichton](https://www.youtube.com/watch?v=agzf6ftEsLU)\n\n### Axioms of Rust\n\n#### Ownership and Borrowing\n- There is only ever **one owner of data**\n- Ownership can be transferred to a new owner; this is known as a **move**.\n- Ownership is a **deep property** of a type\n- Owned values can be **borrowed temporarily**\n- Borrowed values are only valid for a **particular lifetime**\n- **Borrowing prevents moving** -- while there is an active borrow, the owner cannot be moved\n- Borrows can be nested\n- Borrowed values can become owned values through **cloning**\n\n#### Memory Management\n- Each variable has **a scope it is valid for**, and it is **automatically deallocated** when it goes out of scope\n- Reference counting is another way of managing memory -- RC type\n- Rust has shared memory but you must **explicitly opt into it**\n\n#### Mutability\n- Values are **immutable by default**\n- Mutability is also part of the type of a borrowed pointer\n- Borrowed pointers may coerce\n- Values can be **frozen by borrowing**\n- **Mutability propagates deeply** into owned types (just like ownership does)\n\n#### Concurrency\n- Rust's channels enforce thread isolation\n- Thread safety isn't just documentation; it's the law\n- Even the most daring forms of sharing are guaranteed safe in Rust\n- Lock data; not code is enforced in Rust\n\n\n## Iterators [Rust Camp 2015 - Who Owns this Stream of Data?](https://www.youtube.com/watch?v=NGW17shYtRM)\nWhy are there so many types of Iterators in Rust?  The answer lies in Ownership.\n\n### IntoIter - Owned Values (T)\n- Moves the data out of the collection\n- You get total ownership\n- Can do anything with the data, including destroy it\n\n```Rust\nfn process(data: Vec\u003cString\u003e){\n\tfor s in data.into_iter() {\n\t\tprintln!(\"{}\", s);\n\t}\n\n    // Oh no! Iterating consumed it :(\n\tprintln!(\"{}\", data.len()); //~ERROR\n}\n```\n\n### Iter - Shared References (\u0026T)\n- Iter lets you look but not touch :)\n- Shares the data in the collection\n- Read-only access\n- Can have many readers at once\n\n```Rust\nfn print(data: \u0026Vec\u003cString\u003e){\n\tfor s in data.iter(){\n\t\t//All I can do is read :/\n\t\tprintln!(\"{}\", s);\n\t}\n    // Yay it lives!\n\tprintln!(\"{}\", data.len());\n}\n```\n\n### IterMut - Mutable References (\u0026mut T)\n- Loans the data in the collection\n- Read-Write access\n- Only one loan at once\n- IterMut gives you exclusive access\n\n```Rust\nfn make_better(data: \u0026mut Vec\u003cString\u003e){\n\tfor s in data.iter_mut(){\n\t\t//Ooh I can mutate you!\n\t\ts.push_str(\"!!!!\");\n\t\t//But I can't share :(\n\t}\n}\n```\n\n### Drain - I Drink Your Milkshake (Milkshake T) \n- Drain lets you partially move the data\n- Full access to the elements\n- Doesn't destroy the container\n\n```Rust\nlet mut data = vec![0, 1, 2, 3, 4, 5];\n\nfor x in data.drain(2..4){\n\t// got exclusive access so we can \"drain\"\n\t// the values out but leave the vec alive\n\tconsume(x);\n}\n\n// data lives on! We can reuse the allocation!\n// Bulk `remove`!\nassert_eq!(\u0026*data, \u0026[0, 1, 4, 5]);\n```\n\n\n## [LamdaConf 2015 - In Rust we Trust Alex Burkhart](https://www.youtube.com/watch?v=-dxqbhLIgdM)\n\n### Data Race\n- 2 + threads accessing the same data\n- at least 1 is unsynchronized\n- at least 1 is writing\n\n### Shared Nothing\n\n```Rust\nuse std::sync::mpsc::channel;\nuse std::thread;\n\nfn main() {\n    let (tx, rx) = channel();\n\n    for task_num in 0..8 {\n        let tx = tx.clone();\n        thread::spawn(move || {\n            let msg = format!(\"Task {:?} done!\", task_num);\n            tx.send(msg).unwrap();\n        });\n    }\n\n    drop(tx); // Effectively closes the channel\n\n    for data in rx {\n        println!(\"{:?}\", data);\n    }\n}\n```\n\n### Shared Immutable Memory\n\n```Rust\nuse std::sync::mpsc::channel;\nuse std::thread;\nuse std::sync::Arc;\n\nstruct HugeStruct{\n   name: String\n}\n\nfn main() {\n    let (tx, rx) = channel();\n    let huge_struct = HugeStruct{name:\"Ralph\".into()};\n    let arc = Arc::new(huge_struct);\n\n    for task_num in 0..8 {\n        let tx = tx.clone();\n        let arc = arc.clone();\n        thread::spawn(move || {\n            let msg = format!(\"Task {:?} Accessed {:?}\", task_num, arc.name);\n            tx.send(msg).unwrap();\n        });\n    }\n\n    drop(tx); // Effectively closes the channel\n\n    for data in rx {\n        println!(\"{:?}\", data);\n    }\n}\n```\n\n### Mutation with Synchronization\n```Rust\nuse std::sync::mpsc::channel;\nuse std::thread;\nuse std::sync::Arc;\nuse std::sync::Mutex;\n\nstruct HugeStruct{\n   name: String,\n   access_count: i32\n}\n\nfn main() {\n    let (tx, rx) = channel();\n    let huge_struct = HugeStruct{name:\"Ralph\".into(), access_count:0};\n    let arc = Arc::new(Mutex::new(huge_struct));\n\n    for task_num in 0..8 {\n        let tx = tx.clone();\n        let arc = arc.clone();\n        thread::spawn(move || {\n            let mut guard = arc.lock().unwrap();\n            guard.access_count +=1;\n            let msg = format!(\"Task {:?} Accessed {:?} Name {:?}\", task_num, guard.access_count, guard.name);\n            tx.send(msg).unwrap();\n        });\n    }\n\n    drop(tx); // Effectively closes the channel\n\n    for data in rx {\n        println!(\"{:?}\", data);\n    }\n}\n```\n\n### [Fun Example: A generator function](http://stackoverflow.com/a/31392115/71079)\n```Rust\nuse std::thread;\nuse std::sync::mpsc;\n\nfn gen_range(start: i32, end: i32) -\u003e mpsc::Receiver\u003ci32\u003e {\n    let (tx, rx) = mpsc::channel::\u003ci32\u003e();\n    thread::spawn(move || {\n        for i in start..end {\n            tx.send(i).unwrap();\n        }\n        drop(tx);\n    });\n    return rx;\n}\n\nfn main() {\n    let range = gen_range(0, 50);\n    \n    for x in range {\n        println!(\"{}\", x);\n    }\n}\n```\n\n### Ranges, Arrays, Slices, Vectors, Iterators oh my...\n\n#### [Ranges](http://killercup.github.io/trpl-ebook/trpl-2015-09-26.a4.pdf)\n```Rust\n \t// Key take-aways: \n    // - Ranges start off as iterators (notice no need to convert)\n    // - Ranges can represent infinite sequences\n    // - Collecting must occur due to lazy evaluation\n    \n    // This does not actually generate anything\n    let nums = 1..100;\n    \n    // It must be consumed\n    let nums = (1..100).collect::\u003cVec\u003ci32\u003e\u003e();\n\n    // Collect a range into a vector\n    let one_to_one_hundred = (1..101).collect::\u003cVec\u003c_\u003e\u003e();\n    print_type_of(\u0026one_to_one_hundred); //std::vec::Vec\u003ci32\u003e\n\n    // Find numbers in range returning an Option\n    let greater_than_forty_two = (0..100).find(|x| *x \u003e 42);\n    print_type_of(\u0026greater_than_forty_two); //std::option::Option\u003ci32\u003e\n\n    match greater_than_forty_two {\n        Some(_) =\u003e println!(\"We got some numbers!\"),\n        None =\u003e println!(\"No numbers found :(\"),\n    }\n    \n    // Filter numbers in range returning a vector\n    let greater_than_forty_two = (0..100)\n        .filter(|x| *x \u003e 42)\n        .collect::\u003cVec\u003c_\u003e\u003e();\n\n    print_type_of(\u0026greater_than_forty_two); //std::vec::Vec\u003ci32\u003e\n    println!(\"greater_than_forty_two: {:?}\", greater_than_forty_two);\n```\n\n\n### [Let's get functional](https://mmstick.gitbooks.io/rust-programming-phoronix-reader-how-to/content/chapter02.html)\n\n#### With numbers again\n```Rust\nlet numbers_iterator = [0,2,3,4,5].iter();\n\nlet sum = numbers_iterator\n \t.fold(0, |total, next| total + next)\n\t.collect();\n\nlet squared = (1..10).iter()\n\t.map(|\u0026x| x * x).collect();\n```\n\n#### With numbers again\n```Rust\nfn main() {\n    let inf_range = (1..)         // Infinite range of integers\n        .filter(|x| x % 2 != 0)   // Collect odd numbers\n        .take(5)                  // Only take five numbers\n        .map(|x| x * x)           // Square each number\n        .collect::\u003cVec\u003cusize\u003e\u003e(); // Return as a new Vec\u003cusize\u003e\n\n    println!(\"{:?}\", inf_range);  // Print result\n}\n```\n\n#### With Strings\n```Rust\nfn main() {\n    let sentence = \"This is a sentence in Rust.\";\n    let words: Vec\u003c\u0026str\u003e = sentence\n  \t\t.split_whitespace()\n        .collect();\n\n    let words_containing_i: Vec\u003c\u0026str\u003e = words.into_iter()\n        .filter(|word| word.contains(\"i\"))\n        .collect();\n\n    println!(\"{:?}\", words_containing_i);\n}\n```\n\n### What type am I?\nThis feature requires Rust Nightly, this helper method allows for figuring out what type you are working with\nJust pass a reference to it of whatever type you are holding\n\n```Rust\n#![feature(core_intrinsics)]\n\nfn print_type_of\u003cT\u003e(_: \u0026T) -\u003e () {\n    let type_name = unsafe { std::intrinsics::type_name::\u003cT\u003e() };\n    println!(\"{}\", type_name);\n}\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdeckarep%2Frust-notes","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdeckarep%2Frust-notes","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdeckarep%2Frust-notes/lists"}