├── .gitignore ├── Cargo.lock ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── boxing ├── Cargo.toml └── src │ └── main.rs ├── closures ├── Cargo.toml └── src │ └── main.rs ├── conversions ├── Cargo.toml └── src │ └── main.rs ├── errors ├── Cargo.toml └── src │ └── main.rs ├── iterators ├── Cargo.toml └── src │ └── main.rs ├── options-and-results ├── Cargo.toml └── src │ └── main.rs ├── ownership-and-borrowing ├── Cargo.toml └── src │ └── main.rs ├── strings ├── Cargo.toml └── src │ └── main.rs └── threading ├── Cargo.toml └── src └── main.rs /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | 3 | .cargo/ 4 | -------------------------------------------------------------------------------- /Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | version = 3 4 | 5 | [[package]] 6 | name = "anyhow" 7 | version = "1.0.44" 8 | source = "registry+https://github.com/rust-lang/crates.io-index" 9 | checksum = "61604a8f862e1d5c3229fdd78f8b02c68dcf73a4c4b05fd636d12240aaa242c1" 10 | 11 | [[package]] 12 | name = "boxing" 13 | version = "0.1.0" 14 | 15 | [[package]] 16 | name = "closures" 17 | version = "0.1.0" 18 | 19 | [[package]] 20 | name = "conversions" 21 | version = "0.1.0" 22 | 23 | [[package]] 24 | name = "errors" 25 | version = "0.1.0" 26 | dependencies = [ 27 | "anyhow", 28 | ] 29 | 30 | [[package]] 31 | name = "iterators" 32 | version = "0.1.0" 33 | 34 | [[package]] 35 | name = "options-and-results" 36 | version = "0.1.0" 37 | 38 | [[package]] 39 | name = "ownership-and-borrowing" 40 | version = "0.1.0" 41 | 42 | [[package]] 43 | name = "strings" 44 | version = "0.1.0" 45 | 46 | [[package]] 47 | name = "threading" 48 | version = "0.1.0" 49 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | members = ["./ownership-and-borrowing", "options-and-results", "errors", "iterators", "strings", "boxing", "conversions", "closures", "threading"] 3 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Sebastian Thiel and Sidney Douw 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | The repository worked in during episodes of [LRG](https://youtube.com/playlist?list=PLMHbQxe1e9Mk5kOHrm9v20-umkE2ck_gE) for learning Rust with [gitoxide]. 2 | 3 | [gitoxide]: https://github.com/Byron/gitoxide 4 | 5 | ### Episodes - Commit 6 | 7 | * [01 - The essence of Rust](https://youtu.be/LDlBTbO8oQ4) - 405fe8b75689ae0b7a003c90121cc70876e03c84 8 | * [02 - Fancy borrows and zero sized structs](https://youtu.be/ETNW0QlXHYQ) - 4b7dcf5beb3cd98945042e9d0b86c0589519e806 9 | 10 | The above list is currently incomplete. 11 | 12 | ### Authors 13 | 14 | LRG and the files in this repository are by [Sebastian Thiel](https://github.com/Byron) and [Sidney Douw](https://github.com/SidneyDouw). 15 | 16 | ### License 17 | 18 | The files in this repository are licensed under either of 19 | 20 | * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 21 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 22 | 23 | at your option. 24 | -------------------------------------------------------------------------------- /boxing/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "boxing" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | -------------------------------------------------------------------------------- /boxing/src/main.rs: -------------------------------------------------------------------------------- 1 | fn make_iterator(select: bool) -> Box> { 2 | if select { 3 | Box::new([1u32].into_iter()) 4 | } else { 5 | Box::new(vec![0u32].into_iter()) 6 | } 7 | } 8 | 9 | fn use_iterator(iter: impl Iterator) { 10 | for num in iter { 11 | println!("{}", num) 12 | } 13 | } 14 | 15 | fn use_dyn_iterator(iter: &mut dyn Iterator) { 16 | for num in iter { 17 | println!("{}", num) 18 | } 19 | } 20 | 21 | struct MyVec<'a> { 22 | inner: Vec<&'a String>, 23 | } 24 | 25 | impl<'a> MyVec<'a> { 26 | fn iter(&self) -> Box + '_> { 27 | Box::new(self.inner.iter().copied()) 28 | } 29 | } 30 | 31 | fn main() { 32 | use_iterator(make_iterator(true)); 33 | use_iterator([1u32].into_iter()); 34 | 35 | use_dyn_iterator(&mut [1u32].into_iter()); 36 | use_dyn_iterator(&mut make_iterator(true)); 37 | 38 | let other = vec![2u32]; 39 | let empty: Vec; 40 | let iter = if false { 41 | empty = Vec::new(); 42 | empty.iter() 43 | } else { 44 | other.iter() 45 | }; 46 | 47 | for item in iter { 48 | println!("{}", item) 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /closures/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "closures" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | -------------------------------------------------------------------------------- /closures/src/main.rs: -------------------------------------------------------------------------------- 1 | #![allow(dead_code)] 2 | 3 | use std::ops::AddAssign; 4 | 5 | fn main() { 6 | println!("{:?}", map("a", |v| v)); 7 | println!("{:?}", map(4, |v| v + 1)); 8 | fn add_one(v: u32) -> u32 { 9 | v + 1 10 | } 11 | println!("{:?}", map(4, add_one)); 12 | println!( 13 | "{:?}", 14 | map("a".to_string(), |mut v| { 15 | v.push_str("hello"); 16 | v 17 | }) 18 | ); 19 | 20 | let mut count = 0; 21 | println!( 22 | "{:?}", 23 | map("a".to_string(), move |mut v| { 24 | count += 1; 25 | v.push_str("hello"); 26 | v 27 | }) 28 | ); 29 | dbg!(count); 30 | 31 | struct Closure<'a> { 32 | val: Rc>, 33 | } 34 | impl<'a> Closure<'a> { 35 | fn call(&mut self) -> u32 { 36 | self.val.add_assign(1); 37 | *self.val 38 | } 39 | } 40 | } 41 | struct Iter { 42 | map: F, 43 | } 44 | 45 | impl Iter 46 | where 47 | F: FnMut(u32) -> u32, 48 | { 49 | fn next(&mut self) -> u32 { 50 | (self.map)(42) 51 | } 52 | } 53 | fn map(item: T, mut f: impl FnMut(T) -> T) -> T { 54 | let t = f(item); 55 | f(t) 56 | } 57 | -------------------------------------------------------------------------------- /conversions/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "conversions" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | -------------------------------------------------------------------------------- /conversions/src/main.rs: -------------------------------------------------------------------------------- 1 | #![allow(unused)] 2 | 3 | struct A; 4 | struct B; 5 | struct C; 6 | 7 | impl From for A { 8 | fn from(_: B) -> Self { 9 | A 10 | } 11 | } 12 | impl From for A { 13 | fn from(_: C) -> Self { 14 | A 15 | } 16 | } 17 | 18 | fn foo(a: impl Into) { 19 | let a = a.into(); 20 | } 21 | fn foo_b(a: B) { 22 | foo_inner(a.into()) 23 | } 24 | fn foo_c(a: C) { 25 | foo_inner(a.into()) 26 | } 27 | fn foo_inner(a: A) { 28 | // millions of lines 29 | } 30 | 31 | enum Z { 32 | A, 33 | ParsedC, 34 | } 35 | 36 | impl From for Z { 37 | fn from(_: A) -> Self { 38 | Z::A 39 | } 40 | } 41 | 42 | impl TryFrom for Z { 43 | type Error = (); 44 | 45 | fn try_from(value: C) -> Result { 46 | Err(()) 47 | } 48 | } 49 | 50 | fn main() { 51 | let a: A = B.into(); 52 | let a = Into::::into(B); 53 | let a = A::from(B); 54 | let a = A::from(C); 55 | let a: A = C.into(); 56 | 57 | let x: u32 = "8".parse().unwrap(); 58 | let z: Z = A.into(); 59 | let z: Z = A.try_into().unwrap(); 60 | let z: Z = C.try_into().unwrap(); 61 | 62 | foo(B); 63 | foo(C); 64 | foo(A); 65 | } 66 | -------------------------------------------------------------------------------- /errors/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "errors" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | anyhow = "1.0.44" 10 | -------------------------------------------------------------------------------- /errors/src/main.rs: -------------------------------------------------------------------------------- 1 | use anyhow::Context; 2 | use std::error::Error; 3 | use std::fmt::{Display, Formatter}; 4 | 5 | #[derive(Debug)] 6 | enum OutOfBoundsError { 7 | Overflow, 8 | Underflow, 9 | } 10 | 11 | impl Display for OutOfBoundsError { 12 | fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { 13 | write!(f, "{:?}", self) 14 | } 15 | } 16 | 17 | impl Error for OutOfBoundsError {} 18 | 19 | impl From for String { 20 | fn from(v: OutOfBoundsError) -> Self { 21 | format!("{:?}", v) 22 | } 23 | } 24 | 25 | struct Adder<'a>(&'a i8); 26 | 27 | impl<'a> Adder<'a> { 28 | fn add_one(&self) -> Result { 29 | self.0.checked_add(1).ok_or(OutOfBoundsError::Overflow) 30 | } 31 | 32 | fn sub_one(&self) -> Result { 33 | self.0.checked_sub(1).ok_or(OutOfBoundsError::Underflow) 34 | } 35 | } 36 | 37 | fn always_err() -> anyhow::Result<()> { 38 | // anyhow::bail!("hello, failure") 39 | Err(anyhow::anyhow!("hello too")) 40 | } 41 | 42 | fn do_it() -> anyhow::Result<()> { 43 | let v = Adder(&126).add_one()?; 44 | always_err().context("additional information")?; 45 | println!("{}", v); 46 | Adder(&-128).sub_one()?; 47 | Ok(()) 48 | } 49 | 50 | fn main() -> anyhow::Result<()> { 51 | do_it()?; 52 | Ok(()) 53 | } 54 | -------------------------------------------------------------------------------- /iterators/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "iterators" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | -------------------------------------------------------------------------------- /iterators/src/main.rs: -------------------------------------------------------------------------------- 1 | use std::string::FromUtf8Error; 2 | 3 | fn main() -> Result<(), FromUtf8Error> { 4 | let v = [&b"1"[..], &*b"22", b"1"]; 5 | v.into_iter() 6 | .filter_map(|v| String::from_utf8(v.into()).ok()); 7 | Ok(()) 8 | } 9 | -------------------------------------------------------------------------------- /options-and-results/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "options-and-results" 3 | version = "0.1.0" 4 | edition = "2018" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | -------------------------------------------------------------------------------- /options-and-results/src/main.rs: -------------------------------------------------------------------------------- 1 | #![allow(unused, dead_code)] 2 | 3 | fn add_one_safely(v: u8) -> Result { 4 | v.checked_add(1).ok_or("overflow") 5 | } 6 | 7 | fn main() -> Result<(), &'static str> { 8 | (std::env::args().len() == 1) 9 | .then(|| "need two args") 10 | .map(Err::<(), _>) 11 | .transpose()?; 12 | println!("{}", add_one_safely(255)?); 13 | Ok(()) 14 | } 15 | -------------------------------------------------------------------------------- /ownership-and-borrowing/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "ownership-and-borrowing" 3 | version = "0.1.0" 4 | edition = "2018" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | -------------------------------------------------------------------------------- /ownership-and-borrowing/src/main.rs: -------------------------------------------------------------------------------- 1 | #![allow(dead_code, unused_variables)] 2 | 3 | #[derive(Clone)] 4 | struct Foo { 5 | hello: String, 6 | world: String, 7 | } 8 | 9 | #[derive(Clone)] 10 | struct Bar<'a, 'b> { 11 | hello: &'a str, 12 | world: &'b str, 13 | } 14 | 15 | impl Drop for Foo { 16 | fn drop(&mut self) { 17 | println!("{}", self.hello); 18 | } 19 | } 20 | 21 | fn kung_foo<'a>(_a: &'a Foo, _b: &Foo) -> &'a String { 22 | &_a.world 23 | } 24 | 25 | fn main() { 26 | let x = Foo { 27 | hello: "x".to_string(), 28 | world: "world".to_string(), 29 | }; 30 | let field = { 31 | let y = Foo { 32 | hello: "y".to_string(), 33 | world: "world".to_string(), 34 | }; 35 | kung_foo(&x, &y) 36 | }; 37 | 38 | let field = { 39 | let hello = String::from("hello"); 40 | let x = Bar { 41 | hello: hello.as_str(), 42 | world: "world", 43 | }; 44 | x.world 45 | }; 46 | } 47 | -------------------------------------------------------------------------------- /strings/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "strings" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | -------------------------------------------------------------------------------- /strings/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let s: &'static str = "hello😅👋🏼👋🏿你好"; 3 | for char in s.chars() { 4 | println!("{}", char) 5 | } 6 | println!( 7 | "{} = sizeof(char) ({} = MAX chars, unlike {} u32 MAX)", 8 | std::mem::size_of::(), 9 | char::MAX as u32, 10 | u32::MAX 11 | ); 12 | println!("{:?}", &s[..9]); 13 | s.to_owned().push('c'); 14 | s.to_owned().push_str("c"); 15 | } 16 | -------------------------------------------------------------------------------- /threading/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "threading" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | -------------------------------------------------------------------------------- /threading/src/main.rs: -------------------------------------------------------------------------------- 1 | #![allow(unused)] 2 | 3 | use std::cell::RefCell; 4 | use std::sync::{Arc, Mutex}; 5 | 6 | fn main() { 7 | let val = Arc::new(vec![42, 10]); 8 | let mut change = Arc::new(Mutex::new(52)); 9 | let t = vec![ 10 | std::thread::spawn({ 11 | let val = Arc::clone(&val); 12 | let change = change.clone(); 13 | move || { 14 | println!("work: {}", val[0]); 15 | *change.lock().unwrap() += 10; 16 | } 17 | }), 18 | std::thread::spawn({ 19 | let val = val.clone(); 20 | move || { 21 | println!("work: {}", val[1]); 22 | } 23 | }), 24 | ]; 25 | dbg!(&val); 26 | 27 | println!("other work"); 28 | for thread in t { 29 | println!("{:?}", thread.join().unwrap()); 30 | } 31 | dbg!(change); 32 | } 33 | --------------------------------------------------------------------------------