update repo layout

This commit is contained in:
sunface
2022-03-23 20:04:00 +08:00
parent e2d3027b60
commit c1d8b06518
111 changed files with 958 additions and 4 deletions

View File

@@ -0,0 +1,186 @@
# Reference and Borrowing
### Reference
1. 🌟
```rust,editable
fn main() {
let x = 5;
// fill the blank
let p = __;
println!("the memory address of x is {:p}", p); // one possible output: 0x16fa3ac84
}
```
2. 🌟
```rust,editable
fn main() {
let x = 5;
let y = &x;
// modify this line only
assert_eq!(5, y);
println!("Success!")
}
```
3. 🌟
```rust,editable
// fix error
fn main() {
let mut s = String::from("hello, ");
borrow_object(s);
println!("Success!")
}
fn borrow_object(s: &String) {}
```
4. 🌟
```rust,editable
// fix error
fn main() {
let mut s = String::from("hello, ");
push_str(s);
println!("Success!")
}
fn push_str(s: &mut String) {
s.push_str("world")
}
```
5. 🌟🌟
```rust,editable
fn main() {
let mut s = String::from("hello, ");
// fill the blank to make it work
let p = __;
p.push_str("world");
println!("Success!")
}
```
#### ref
`ref` can be used to take references to a value, similar to `&`.
6. 🌟🌟🌟
```rust,editable
fn main() {
let c = '中';
let r1 = &c;
// fill the blankdont change other code
let __ r2 = c;
assert_eq!(*r1, *r2);
// check the equality of the two address strings
assert_eq!(get_addr(r1),get_addr(r2));
println!("Success!")
}
// get memory address string
fn get_addr(r: &char) -> String {
format!("{:p}", r)
}
```
### Borrowing rules
7. 🌟
```rust,editable
// remove something to make it work
// don't remove a whole line !
fn main() {
let mut s = String::from("hello");
let r1 = &mut s;
let r2 = &mut s;
println!("{}, {}", r1, r2);
println!("Success!")
}
```
#### Mutablity
8. 🌟 Error: Borrow a immutable object as mutable
```rust,editable
fn main() {
//fix error by modifying this line
let s = String::from("hello, ");
borrow_object(&mut s);
println!("Success!")
}
fn borrow_object(s: &mut String) {}
```
9. 🌟🌟 Ok: Borrow a mutable object as immutable
```rust,editable
// this code has no errors!
fn main() {
let mut s = String::from("hello, ");
borrow_object(&s);
s.push_str("world");
println!("Success!")
}
fn borrow_object(s: &String) {}
```
### NLL
10. 🌟🌟
```rust,editable
// comment one line to make it work
fn main() {
let mut s = String::from("hello, ");
let r1 = &mut s;
r1.push_str("world");
let r2 = &mut s;
r2.push_str("!");
println!("{}",r1);
}
```
11. 🌟🌟
```rust,editable
fn main() {
let mut s = String::from("hello, ");
let r1 = &mut s;
let r2 = &mut s;
// add one line below to make a compiler error: cannot borrow `s` as mutable more than once at a time
// you can't use r1 and r2 at the same time
}
```
> You can find the solutions [here](https://github.com/sunface/rust-by-practice)(under the solutions path), but only use it when you need it

View File

@@ -0,0 +1,5 @@
# Ownership and Borrowing
Learning resources:
- English: [Rust Book 4.1-4.4](https://doc.rust-lang.org/book/ch04-00-understanding-ownership.html)
- 简体中文: [Rust语言圣经 - 所有权与借用](https://course.rs/basic/ownership/index.html)

View File

@@ -0,0 +1,170 @@
# Ownership
1. 🌟🌟
```rust,editable
fn main() {
// use as many approaches as you can to make it work
let x = String::from("hello, world");
let y = x;
println!("{},{}",x,y);
}
```
2. 🌟🌟
```rust,editable
// Don't modify code in main!
fn main() {
let s1 = String::from("hello, world");
let s2 = take_ownership(s1);
println!("{}", s2);
}
// Only modify the code below!
fn take_ownership(s: String) {
println!("{}", s);
}
```
3. 🌟🌟
```rust,editable
fn main() {
let s = give_ownership();
println!("{}", s);
}
// Only modify the code below!
fn give_ownership() -> String {
let s = String::from("hello, world");
// convert String to Vec
let _s = s.into_bytes();
s
}
```
4. 🌟🌟
```rust,editable
// fix the error without removing code line
fn main() {
let s = String::from("hello, world");
print_str(s);
println!("{}", s);
}
fn print_str(s: String) {
println!("{}",s)
}
```
5. 🌟🌟
```rust, editable
// don't use clone ,use copy instead
fn main() {
let x = (1, 2, (), "hello".to_string());
let y = x.clone();
println!("{:?}, {:?}", x, y);
}
```
#### Mutability
Mutability can be changed when ownership is transferred.
6. 🌟
```rust,editable
fn main() {
let s = String::from("hello, ");
// modify this line only !
let s1 = s;
s1.push_str("world");
println!("Success!")
}
```
7. 🌟🌟🌟
```rust,editable
fn main() {
let x = Box::new(5);
let ... // implement this line, dont change other lines!
*y = 4;
assert_eq!(*x, 5);
println!("Success!")
}
```
### Partial move
Within the destructuring of a single variable, both by-move and by-reference pattern bindings can be used at the same time. Doing this will result in a partial move of the variable, which means that parts of the variable will be moved while other parts stay. In such a case, the parent variable cannot be used afterwards as a whole, however the parts that are only referenced (and not moved) can still be used.
#### Example
```rust,editable
fn main() {
#[derive(Debug)]
struct Person {
name: String,
age: Box<u8>,
}
let person = Person {
name: String::from("Alice"),
age: Box::new(20),
};
// `name` is moved out of person, but `age` is referenced
let Person { name, ref age } = person;
println!("The person's age is {}", age);
println!("The person's name is {}", name);
// Error! borrow of partially moved value: `person` partial move occurs
//println!("The person struct is {:?}", person);
// `person` cannot be used but `person.age` can be used as it is not moved
println!("The person's age from person struct is {}", person.age);
}
```
#### Exercises
8. 🌟
```rust,editable
fn main() {
let t = (String::from("hello"), String::from("world"));
let _s = t.0;
// modify this line only, don't use `_s`
println!("{:?}", t);
}
```
9. 🌟🌟
```rust,editable
fn main() {
let t = (String::from("hello"), String::from("world"));
// fill the blanks
let (__, __) = __;
println!("{:?}, {:?}, {:?}", s1, s2, t); // -> "hello", "world", ("hello", "world")
}
```
> You can find the solutions [here](https://github.com/sunface/rust-by-practice)(under the solutions path), but only use it when you need it