format code in md

This commit is contained in:
likzn 2022-05-01 13:08:50 +08:00
parent dad4052485
commit e09080f88a
43 changed files with 405 additions and 124 deletions

View File

@ -1,28 +1,32 @@
1.
```rust
use std::mem::size_of_val;
fn main() {
let c1 = 'a';
assert_eq!(size_of_val(&c1),4);
assert_eq!(size_of_val(&c1), 4);
let c2 = '中';
assert_eq!(size_of_val(&c2),4);
assert_eq!(size_of_val(&c2), 4);
}
```
2.
```rust
fn main() {
let c1 = '中';
print_char(c1);
}
}
fn print_char(c : char) {
fn print_char(c: char) {
println!("{}", c);
}
```
3.
```rust
fn main() {
let _f: bool = false;
@ -35,6 +39,7 @@ fn main() {
```
4.
```rust
fn main() {
let f = true;
@ -44,6 +49,7 @@ fn main() {
```
5.
```rust
fn main() {
let v0: () = ();
@ -63,8 +69,10 @@ fn explicitly_ret_unit() -> () {
```
6.
```rust
use std::mem::size_of_val;
fn main() {
let unit: () = ();
// unit type does't occupy any memeory space

View File

@ -1,4 +1,5 @@
1.
```rust
fn main() {
// don't modify the following two lines!
@ -14,6 +15,7 @@ fn sum(x: i32, y: i32) -> i32 {
```
2.
```rust
fn main() {
print();
@ -26,6 +28,7 @@ fn print() -> () {
```
3.
```rust
fn main() {
never_return();
@ -44,6 +47,7 @@ fn main() {
use std::thread;
use std::time;
fn never_return() -> ! {
// implement this function, don't modify fn signatures
loop {
@ -55,6 +59,7 @@ fn never_return() -> ! {
```
4.
```rust
fn main() {
println!("Success!");
@ -69,7 +74,7 @@ fn get_option(tp: u8) -> Option<i32> {
// TODO
}
};
never_return_fn()
}
@ -97,6 +102,7 @@ fn never_return_fn() -> ! {
```
5.
```rust
fn main() {
// FILL in the blank

View File

@ -1,4 +1,5 @@
1.
```rust
fn main() {
let x: i32 = 5;
@ -11,6 +12,7 @@ fn main() {
```
2.
```rust
fn main() {
let v: u16 = 38_u8 as u16;
@ -18,6 +20,7 @@ fn main() {
```
3.
```rust
fn main() {
let x = 5;
@ -31,6 +34,7 @@ fn type_of<T>(_: &T) -> String {
```
4.
```rust
fn main() {
assert_eq!(i8::MAX, 127);
@ -39,6 +43,7 @@ fn main() {
```
5.
```rust
fn main() {
let v1 = 247_u8 + 8;
@ -48,6 +53,7 @@ fn main() {
```
6.
```rust
fn main() {
let v = 1_024 + 0xff + 0o77 + 0b1111_1111;
@ -56,6 +62,7 @@ fn main() {
```
7.
```rust
fn main() {
let x = 1_000.000_1; // f64
@ -65,6 +72,7 @@ fn main() {
```
8.
```rust
fn main() {
assert!(0.1_f32+0.2_f32==0.3_f32);
@ -78,6 +86,7 @@ fn main() {
```
9.
```rust
fn main() {
let mut sum = 0;
@ -94,6 +103,7 @@ fn main() {
```
10.
```rust
use std::ops::{Range, RangeInclusive};
fn main() {
@ -103,6 +113,7 @@ fn main() {
```
11.
```rust
fn main() {
// Integer addition

View File

@ -1,4 +1,5 @@
1.
```rust
fn main() {
let v = {
@ -23,6 +24,7 @@ fn main() {
```
2.
```rust
fn main() {
let v = {
@ -35,6 +37,7 @@ fn main() {
```
3.
```rust
fn main() {
let s = sum(1 , 2);

View File

@ -1,4 +1,5 @@
1.
```rust
// FILL in the blanks and FIX the erros
use std::collections::HashMap;
@ -29,6 +30,7 @@ fn main() {
```
2.
```rust
use std::collections::HashMap;
fn main() {
@ -73,9 +75,11 @@ fn main() {
```
3.
```rust
// FILL in the blanks
use std::collections::HashMap;
fn main() {
// type inference lets us omit an explicit type signature (which
// would be `HashMap<&str, u8>` in this example).
@ -109,6 +113,7 @@ fn random_stat_buff() -> u8 {
```
4.
```rust
use std::collections::HashMap;
@ -144,19 +149,21 @@ fn main() {
```
5.
```rust
use std::collections::HashMap;
fn main() {
let v1 = 10;
let mut m1 = HashMap::new();
m1.insert(v1, v1);
println!("v1 is still usable after inserting to hashmap : {}", v1);
// &str implements Copy trait
let v2 = "hello";
let mut m2 = HashMap::new();
m2.insert(v2, v1);
assert_eq!(v2, "hello");
fn main() {
let v1 = 10;
let mut m1 = HashMap::new();
m1.insert(v1, v1);
println!("v1 is still usable after inserting to hashmap : {}", v1);
// &str implements Copy trait
let v2 = "hello";
let mut m2 = HashMap::new();
m2.insert(v2, v1);
assert_eq!(v2, "hello");
}
```

View File

@ -1,4 +1,5 @@
1.
```rust
fn main() {
let mut s: String = String::from("hello, ");
@ -36,6 +37,7 @@ fn borrow_string(s: &str) {
```
2.
```rust
// FILL in the blanks
fn main() {
@ -82,6 +84,7 @@ fn main() {
4.
```rust
fn main() {
let s = String::from("hello, 世界");
@ -102,6 +105,7 @@ fn main() {
```
5.
```rust
// FILL in the blanks
fn main() {
@ -123,6 +127,7 @@ fn main() {
```
6.
```rust
fn main() {
let mut s = String::with_capacity(25);
@ -139,6 +144,7 @@ fn main() {
```
7.
```rust
use std::mem;

View File

@ -1,4 +1,5 @@
1.
1.
```rust
fn main() {
let arr: [u8; 3] = [1, 2, 3];
@ -30,6 +31,7 @@ fn is_vec(v: &Vec<u8>) {}
```
2.
```rust
fn main() {
let mut v1 = Vec::from([1, 2, 4]);
@ -45,7 +47,8 @@ fn main() {
}
```
3.
3.
```rust
fn main() {
// array -> Vec
@ -72,7 +75,8 @@ fn main() {
}
```
4.
4.
```rust,editable
fn main() {
let mut v = Vec::from([1, 2, 3]);
@ -94,7 +98,8 @@ fn main() {
}
```
5.
5.
```rust
// FIX the errors
fn main() {
@ -119,7 +124,8 @@ fn main() {
}
```
6.
6.
```rust
// FIX the errors
fn main() {
@ -155,20 +161,22 @@ fn main() {
}
```
7.
7.
```rust
#[derive(Debug, PartialEq)]
enum IpAddr {
V4(String),
V6(String),
}
fn main() {
// FILL in the blank
let v : Vec<IpAddr>= vec![
let v: Vec<IpAddr> = vec![
IpAddr::V4("127.0.0.1".to_string()),
IpAddr::V6("::1".to_string())
];
// Comparing two enums need to derive the PartialEq trait
assert_eq!(v[0], IpAddr::V4("127.0.0.1".to_string()));
assert_eq!(v[1], IpAddr::V6("::1".to_string()));
@ -177,7 +185,8 @@ fn main() {
}
```
8.
8.
```rust
trait IpAddr {
fn display(&self);

View File

@ -1,4 +1,5 @@
1.
```rust
fn main() {
let arr: [i32; 5] = [1, 2, 3, 4, 5];
@ -8,12 +9,13 @@ fn main() {
```
2.
```rust
fn main() {
// we can ignore parts of the array type or even the whole type, let the compiler infer it for us
let arr0 = [1, 2, 3];
let arr: [_; 3] = ['a', 'b', 'c'];
// Arrays are stack allocated, `std::mem::size_of_val` return the bytes which array occupies
// A char takes 4 byte in Rust: Unicode char
assert!(std::mem::size_of_val(&arr) == 12);
@ -21,6 +23,7 @@ fn main() {
```
3.
```rust
fn main() {
let list: [i32; 100] = [1; 100];
@ -31,6 +34,7 @@ fn main() {
```
4.
```rust
fn main() {
// fix the error
@ -39,10 +43,11 @@ fn main() {
```
5.
```rust
fn main() {
let arr = ['a', 'b', 'c'];
let ele = arr[0];
assert!(ele == 'a');
@ -50,10 +55,11 @@ fn main() {
```
6.
```rust
fn main() {
let names = [String::from("Sunfei"), "Sunface".to_string()];
// `get` returns an Option<T>, it's safe to use
let name0 = names.get(0).unwrap();

View File

@ -1,4 +1,5 @@
1.
```rust
enum Number {
Zero,
@ -28,6 +29,7 @@ fn main() {
```
2.
```rust
enum Message {
Quit,
@ -43,6 +45,7 @@ fn main() {
```
3.
```rust
enum Message {
Quit,
@ -63,6 +66,7 @@ fn main() {
```
4.
```rust
#[derive(Debug)]
enum Message {
@ -75,14 +79,14 @@ enum Message {
fn main() {
let msgs: [Message; 3] = [
Message::Quit,
Message::Move{x:1, y:3},
Message::ChangeColor(255,255,0)
Message::Move { x: 1, y: 3 },
Message::ChangeColor(255, 255, 0)
];
for msg in msgs {
show_message(msg)
}
}
}
fn show_message(msg: Message) {
println!("{:?}", msg);
@ -90,6 +94,7 @@ fn show_message(msg: Message) {
```
5.
```rust
fn main() {
let five = Some(5);
@ -113,6 +118,7 @@ fn plus_one(x: Option<i32>) -> Option<i32> {
```
6.
```rust
use crate::List::*;
@ -162,10 +168,10 @@ impl List {
// `format!` is similar to `print!`, but returns a heap
// allocated string instead of printing to the console
format!("{}, {}", head, tail.stringify())
},
}
Nil => {
format!("Nil")
},
}
}
}
}

View File

@ -1,4 +1,5 @@
1.
```rust
fn main() {
let arr = [1, 2, 3];
@ -9,18 +10,20 @@ fn main() {
```
2.
```rust
fn main() {
let arr: [char; 3] = ['中', '国', '人'];
let slice = &arr[..2];
// TIPS: slice( reference ) IS NOT an array, if it is an array, then `assert!` will passed: each of the two UTF-8 chars '中' and '国' occupies 3 bytes, 2 * 3 = 6
assert!(std::mem::size_of_val(&slice) == 16);
}
```
3.
```rust
fn main() {
let arr: [i32; 5] = [1, 2, 3, 4, 5];
@ -30,6 +33,7 @@ fn main() {
```
4.
```rust
fn main() {
let s = String::from("hello");
@ -42,6 +46,7 @@ fn main() {
```
5.
```rust
fn main() {
let s = "你好,世界";
@ -52,6 +57,7 @@ fn main() {
```
6.
```rust
fn main() {
let mut s = String::from("hello world");
@ -63,8 +69,8 @@ fn main() {
println!("the first word is: {}", word);
s.clear();
}
fn first_word(s: &str) -> &str {
&s[..1]
}

View File

@ -1,11 +1,13 @@
1.
1.
```rust
fn main() {
let s: &str = "hello, world";
}
```
2.
2.
```rust
fn main() {
let s: Box<str> = "hello, world".into();
@ -16,6 +18,7 @@ fn main() {
println!("{}",s)
}
```
```rust
fn main() {
let s: Box<&str> = "hello, world".into();
@ -27,7 +30,8 @@ fn greetings(s: &str) {
}
```
3.
3.
```rust
fn main() {
let mut s = String::new();
@ -38,7 +42,8 @@ fn main() {
}
```
4.
4.
```rust
fn main() {
let mut s = String::from("hello");
@ -50,7 +55,8 @@ fn main() {
}
```
5.
5.
```rust
fn main() {
let s = String::from("I like dogs");
@ -61,7 +67,8 @@ fn main() {
}
```
6.
6.
```rust
fn main() {
let s1 = String::from("hello,");
@ -72,7 +79,8 @@ fn main() {
}
```
7.
7.
```rust
fn main() {
let s = "hello, world".to_string();
@ -95,10 +103,11 @@ fn greetings(s: String) {
}
```
8.
8.
```rust
fn main() {
let s = "hello, world".to_string();
let s = "hello, world".to_string();
let s1: &str = &s;
}
```
@ -112,12 +121,13 @@ fn main() {
```rust
fn main() {
let s = "hello, world".to_string();
let s = "hello, world".to_string();
let s1: String = s;
}
```
9.
9.
```rust
fn main() {
// You can use escapes to write bytes by their hexadecimal values
@ -140,7 +150,8 @@ fn main() {
}
```
10.
10.
```rust
fn main() {
let raw_str = "Escapes don't work here: \x3F \u{211D}";
@ -162,7 +173,8 @@ fn main() {
}
```
11.
11.
```rust
fn main() {
let s1 = String::from("hi,中国");
@ -174,7 +186,8 @@ fn main() {
}
```
12.
12.
```rust
fn main() {
for c in "你好,世界".chars() {

View File

@ -1,4 +1,5 @@
1.
```rust
struct Person {
name: String,
@ -16,6 +17,7 @@ fn main() {
```
2.
```rust
struct Unit;
trait SomeTrait {
@ -35,6 +37,7 @@ fn do_something_with_unit(u: Unit) { }
```
3.
```rust
struct Color(i32, i32, i32);
struct Point(i32, i32, i32);
@ -52,6 +55,7 @@ fn check_color(p: Point) {
```
4.
```rust
struct Person {
name: String,
@ -72,6 +76,7 @@ fn main() {
```
5.
```rust
struct Person {
name: String,
@ -88,6 +93,7 @@ fn build_person(name: String, age: u8) -> Person {
```
6.
```rust
struct User {
active: bool,
@ -115,6 +121,7 @@ fn set_email(u: User) -> User {
```
7.
```rust
#[derive(Debug)]
struct Rectangle {
@ -136,6 +143,7 @@ fn main() {
```
8.
```rust
#[derive(Debug)]
struct File {

View File

@ -1,4 +1,5 @@
1.
```rust
fn main() {
let _t0: (u8,i16) = (0, -1);
@ -9,6 +10,7 @@ fn main() {
```
2.
```rust
fn main() {
let t = ("i", "am", "sunface");
@ -17,6 +19,7 @@ fn main() {
```
3.
```rust
fn main() {
let too_long_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12);
@ -25,6 +28,7 @@ fn main() {
```
4.
```rust
fn main() {
let tup = (1, 6.4, "hello");
@ -38,6 +42,7 @@ fn main() {
```
5.
```rust
fn main() {
let (x, y, z);
@ -52,6 +57,7 @@ fn main() {
```
6.
```rust
fn main() {
let (x, y) = sum_multiply((2, 3));

View File

@ -2,13 +2,14 @@
2. `cargo new --lib hello-package1`
3. `hello-package` has a binary crate named `hello-package`, `src/main.rs` is the crate root.
3. `hello-package` has a binary crate named `hello-package`, `src/main.rs` is the crate root.
`hello-pacakge1` has a library crate named `hello-package1`, `src/lib.rs` is the crate root.
4. `hello-package1`
5.
```shell
# FILL in the blanks
.
@ -20,6 +21,7 @@
```
6.
```shell
# Create a package which contains
# 1. three binary crates: `hello-package`, `main1` and `main2`

View File

@ -1,4 +1,5 @@
1.
```rust
// in lib.rs
mod front_of_house {
@ -21,6 +22,7 @@ mod front_of_house {
```
2.
```rust
// in lib.rs
pub mod front_of_house {
@ -53,6 +55,7 @@ pub fn eat_at_restaurant() {
```
3.
```rust
mod back_of_house {
fn fix_incorrect_order() {
@ -75,9 +78,8 @@ mod back_of_house {
}
```
4.
```rust
// in src/lib.rs
@ -104,7 +106,6 @@ pub fn fix_incorrect_order() {
pub fn cook_order() {}
```
```rust
// in src/front_of_house/mod.rs
@ -136,8 +137,8 @@ pub fn take_payment() {}
fn complain() {}
```
5.
```rust
mod front_of_house;

View File

@ -1,4 +1,5 @@
1.
```rust
use std::fmt::Result;
use std::io::Result as IoResult;
@ -7,6 +8,7 @@ fn main() {}
```
2.
```rust
use std::collections::*;
@ -29,8 +31,8 @@ fn main() {
}
```
3.
3.
```rust
// in lib.rs

View File

@ -1,4 +1,5 @@
1.
```rust
struct test {
list: Vec<i32>,

View File

@ -1,11 +1,12 @@
1.
```rust
fn main() {
let n = 5;
if n < 0 {
println!("{} is negative", n);
} else if n > 0 {
} else if n > 0 {
println!("{} is positive", n);
} else {
println!("{} is zero", n);
@ -14,6 +15,7 @@ fn main() {
```
2.
```rust
fn main() {
let n = 5;
@ -26,7 +28,7 @@ fn main() {
} else {
println!(", and is a big number, halve the number");
n / 2
n / 2
};
println!("{} -> {}", n, big_n);
@ -34,9 +36,10 @@ fn main() {
```
3.
```rust
fn main() {
for n in 1..100 {
for n in 1..100 {
if n == 100 {
panic!("NEVER LET THIS RUN")
}
@ -45,9 +48,10 @@ fn main() {
```
4.
```rust
fn main() {
let names = [String::from("liming"),String::from("hanmeimei")];
let names = [String::from("liming"), String::from("hanmeimei")];
for name in &names {
// do something with name...
}
@ -59,24 +63,26 @@ fn main() {
for n in numbers {
// do something with name...
}
println!("{:?}", numbers);
}
```
5.
```rust
fn main() {
let a = [4, 3, 2, 1];
// iterate the indexing and value in 'a'
for (i,v) in a.iter().enumerate() {
println!("The {}th element is {}",i+1,v);
for (i, v) in a.iter().enumerate() {
println!("The {}th element is {}", i + 1, v);
}
}
```
6.
```rust
fn main() {
// A counter variable
@ -98,19 +104,20 @@ fn main() {
n += 1;
}
println!("n reached {}, soloop is over",n);
println!("n reached {}, soloop is over", n);
}
```
7.
```rust
fn main() {
let mut n = 0;
for i in 0..=100 {
if n == 66 {
break
}
n += 1;
if n == 66 {
break;
}
n += 1;
}
assert_eq!(n, 66);
@ -118,16 +125,17 @@ fn main() {
```
8.
```rust
fn main() {
let mut n = 0;
for i in 0..=100 {
if n != 66 {
n+=1;
continue;
}
break
if n != 66 {
n += 1;
continue;
}
break;
}
assert_eq!(n, 66);
@ -135,6 +143,7 @@ fn main() {
```
9.
```rust
fn main() {
let mut count = 0u32;
@ -166,6 +175,7 @@ fn main() {
```
10.
```rust
fn main() {
let mut counter = 0;
@ -183,6 +193,7 @@ fn main() {
```
11.
```rust
fn main() {
let mut count = 0;

View File

@ -1,4 +1,5 @@
1.
```rust
#[derive(Debug)]
struct Structure(i32);
@ -10,7 +11,9 @@ fn main() {
println!("Now {:?} will print!", Structure(3));
}
```
2.
```rust
#[derive(Debug)]
struct Person {
@ -26,6 +29,7 @@ fn main() {
```
3.
```rust
use std::fmt;
@ -48,6 +52,7 @@ fn main() {
```
4
```rust
use std::fmt;
@ -79,6 +84,7 @@ fn main() {
```
5.
```rust
use std::fmt; // Import the `fmt` module.

View File

@ -1,4 +1,5 @@
1.
```rust
fn main() {
println!("{0}, this is {1}. {1}, this is {0}", "Alice", "Bob");// => Alice, this is Bob. Bob, this is Alice
@ -9,6 +10,7 @@ fn main() {
```
2.
```rust
fn main() {
println!("{argument}", argument = "test"); // => "test"
@ -24,6 +26,7 @@ fn main() {
```
3.
```rust
fn main() {
// the following two are padding with 5 spaces
@ -38,6 +41,7 @@ fn main() {
```
4.
```rust
fn main() {
// left align
@ -55,6 +59,7 @@ fn main() {
```
5.
```rust
fn main() {
println!("Hello {:5}!", 5); // => Hello 5!
@ -69,6 +74,7 @@ fn main() {
```
6.
```rust
fn main() {
let v = 3.1415926;
@ -84,6 +90,7 @@ fn main() {
```
7.
```rust
fn main() {
let s = "Hello, world!";
@ -97,6 +104,7 @@ fn main() {
```
8.
```rust
fn main() {
assert_eq!(format!("{:#b}", 27), "0b11011");
@ -113,6 +121,7 @@ fn main() {
```
9.
```rust
fn get_person() -> String {
String::from("sunface")

View File

@ -1,4 +1,5 @@
1.
```rust
fn main() {
let s1 = "hello";
@ -9,6 +10,7 @@ fn main() {
```
2.
```rust
fn main() {
print!("hello world, ");

View File

@ -1,4 +1,5 @@
1、
```rust
fn main() {
let color = String::from("green");
@ -13,6 +14,7 @@ fn main() {
```
2、
```rust
fn main() {
let mut count = 0;
@ -38,6 +40,7 @@ fn main() {
```
3、
```rust
fn main() {
// A non-copy type.
@ -83,6 +86,7 @@ fn take<T>(_v: &T) {
```
4、
```rust
fn main() {
let example_closure = |x| x;
@ -95,6 +99,7 @@ fn main() {
```
5、
```rust
fn fn_once<F>(func: F)
where
@ -126,6 +131,7 @@ fn main() {
```
6、
```rust
fn main() {
let mut s = String::new();
@ -143,6 +149,7 @@ fn exec<'a, F: FnMut(&'a str)>(mut f: F) {
```
7、
```rust
// A function which takes a closure as an argument and calls it.
// <F> denotes that F is a "Generic type parameter"
@ -197,6 +204,7 @@ fn main() {
```
8、
```rust
fn main() {
let mut s = String::new();
@ -212,6 +220,7 @@ fn exec<'a, F: FnOnce(&'a str) -> String>(mut f: F) {
```
9、
```rust
// Define a function which takes a generic `F` argument
// bounded by `Fn`, and calls it
@ -234,6 +243,7 @@ fn main() {
```
10、
```rust
/* Fill in the blank and fix the errror */
// You can aslo use `impl FnOnce(i32) -> i32`
@ -268,6 +278,7 @@ fn main() {
```
11、
```rust
// Every closure has its own type. Even if one closure has the same representation as another, their types are different.
fn factory(x:i32) -> Box<dyn Fn(i32) -> i32> {

View File

@ -1,4 +1,5 @@
1、
```rust
fn main() {
let arr = [0; 10];
@ -9,6 +10,7 @@ fn main() {
```
2、
```rust
fn main() {
let mut v = Vec::new();
@ -21,6 +23,7 @@ fn main() {
```
3、
```rust
fn main() {
let v1 = vec![1, 2];
@ -48,6 +51,7 @@ fn main() {
```
4、
```rust
fn main() {
let arr = vec![0; 10];
@ -60,6 +64,7 @@ fn main() {
```
5、
```rust
fn main() {
let mut names = vec!["Bob", "Frank", "Ferris"];
@ -76,6 +81,7 @@ fn main() {
```
6、
```rust
fn main() {
let mut values = vec![1, 2, 3];
@ -90,6 +96,7 @@ fn main() {
```
7、
```rust
struct Fibonacci {
curr: u32,
@ -136,6 +143,7 @@ fn main() {
```
8、
```rust
fn main() {
let v1 = vec![1, 2, 3];
@ -152,6 +160,7 @@ fn main() {
```
9、
```rust
use std::collections::HashMap;
fn main() {
@ -169,6 +178,7 @@ fn main() {
```
10、
```rust
fn main() {
let v1: Vec<i32> = vec![1, 2, 3];
@ -180,6 +190,7 @@ fn main() {
```
11、
```rust
use std::collections::HashMap;
fn main() {
@ -192,6 +203,7 @@ fn main() {
```
12、
```rust
#[derive(PartialEq, Debug)]
struct Shoe {

View File

@ -1,4 +1,5 @@
1.
```rust
struct Container(i32, i32);
@ -53,6 +54,7 @@ fn main() {
```
2.
```rust
impl<T: Sub<Output = T>> Sub<Point<T>> for Point<T> {
type Output = Self;
@ -93,6 +95,7 @@ impl<T: Sub<Output = T>> Sub for Point<T> {
```
3.
```rust
trait Pilot {
fn fly(&self) -> String;
@ -134,6 +137,7 @@ fn main() {
```
4.
```rust
trait Person {
fn name(&self) -> String;
@ -209,6 +213,7 @@ fn main() {
```
5.
```rust
use std::fmt;

View File

@ -1,4 +1,5 @@
1.
```rust
struct Array<T, const N: usize> {
data : [T; N]
@ -20,6 +21,7 @@ fn main() {
```
2.
```rust
fn print_array<T: std::fmt::Debug, const N: usize>(arr: [T; N]) {
println!("{:?}", arr);
@ -33,7 +35,8 @@ fn main() {
}
```
3.
3.
```rust
#![allow(incomplete_features)]
#![feature(generic_const_exprs)]

View File

@ -1,4 +1,5 @@
1.
```rust
struct A; // Concrete type `A`.
struct S(A); // Concrete type `S`.
@ -27,6 +28,7 @@ fn main() {
```
2.
```rust
fn sum<T:std::ops::Add<Output = T>>(x: T, y: T) -> T {
x + y
@ -39,8 +41,8 @@ fn main() {
}
```
3.
```rust
struct Point<T> {
x: T,
@ -54,6 +56,7 @@ fn main() {
```
4.
```rust
// modify this struct to make the code work
struct Point<T, U> {
@ -68,6 +71,7 @@ fn main() {
```
5.
```rust
struct Val<T> {
val: T,
@ -88,6 +92,7 @@ fn main() {
```
6.
```rust
struct Point<T, U> {
x: T,
@ -115,6 +120,7 @@ fn main() {
```
7.
```rust
struct Point<T> {
x: T,

View File

@ -1,4 +1,5 @@
1.
```rust
trait Bird {
fn quack(&self) -> String;
@ -58,6 +59,7 @@ fn hatch_a_bird(species: u8) ->Box<dyn Bird> {
```
2.
```rust
trait Bird {
fn quack(&self);
@ -101,6 +103,7 @@ fn main() {
```
3.
```rust
trait Draw {
fn draw(&self) -> String;
@ -139,6 +142,7 @@ fn draw_with_ref(x: &dyn Draw) {
```
4.
```rust
trait Foo {
fn method(&self) -> String;
@ -174,6 +178,7 @@ fn main() {
```
5.
```rust
trait MyTrait {
fn f(&self) -> Self;

View File

@ -1,4 +1,5 @@
1.
```rust
trait Hello {
fn say_hi(&self) -> String {
@ -37,6 +38,7 @@ fn main() {
```
2.
```rust
// `Centimeters`, a tuple struct that can be compared
#[derive(PartialEq, PartialOrd)]
@ -84,6 +86,7 @@ fn main() {
```
3.
```rust
use std::ops;
@ -101,6 +104,7 @@ fn main() {
```
4.
```rust
use std::ops;
@ -141,6 +145,7 @@ fn main() {
```
5.
```rust
// implement `fn summary` to make the code work
// fix the errors without removing any code line
@ -197,6 +202,7 @@ fn summary(t: &impl Summary) {
```
6.
```rust
struct Sheep {}
struct Cow {}
@ -272,6 +278,7 @@ fn main() {
```
7.
```rust
fn main() {
assert_eq!(sum(1, 2), 3);
@ -298,6 +305,7 @@ where
```
8.
```rust
struct Pair<T> {
x: T,
@ -337,6 +345,7 @@ fn main() {
```
9.
```rust
fn example1() {
// `T: Trait` is the commonly used way

View File

@ -1,4 +1,5 @@
1、
```rust
struct DoubleRef<'a,'b:'a, T> {
r: &'a T,
@ -9,8 +10,8 @@ fn main() {
}
```
2、
```rust
struct ImportantExcerpt<'a> {
part: &'a str,
@ -29,6 +30,7 @@ fn main() {
```
3、
```rust
fn f<'a, 'b>(x: &'a i32, mut y: &'b i32) where 'a: 'b {
y = x; // &'a i32 is a subtype of &'b i32 because 'a: 'b
@ -39,8 +41,8 @@ fn main() {
}
```
4、
```rust
fn call_on_ref_zero<F>(f: F) where for<'a> F: Fn(&'a i32) {
let zero = 0;
@ -52,7 +54,9 @@ fn main() {
}
```
Higher-ranked lifetimes may also be specified just before the trait: the only difference is the scope of the lifetime parameter, which extends only to the end of the following trait instead of the whole bound. This function is equivalent to the last one.
Higher-ranked lifetimes may also be specified just before the trait: the only difference is the scope of the lifetime
parameter, which extends only to the end of the following trait instead of the whole bound. This function is equivalent
to the last one.
```rust
fn call_on_ref_zero<F>(f: F) where F: for<'a> Fn(&'a i32) {
@ -62,6 +66,7 @@ fn call_on_ref_zero<F>(f: F) where F: for<'a> Fn(&'a i32) {
```
5、
```rust
fn main() {
let mut data = 10;
@ -75,8 +80,8 @@ fn main() {
}
```
6、
```rust
struct Interface<'b, 'a: 'b> {
manager: &'b mut Manager<'a>

View File

@ -1,5 +1,7 @@
# Lifetime
1.
```rust
fn main() {
let i = 3; // Lifetime for `i` starts. ────────────────┐
@ -20,8 +22,8 @@ fn main() {
} // Lifetime ends. ─────────────────────────────────────┘
```
2. We can't borrow a item whose lifetime is smaller.
```rust
fn main() {
{
@ -38,6 +40,7 @@ fn main() {
```
3
```rust
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() {
@ -51,6 +54,7 @@ fn main() {}
```
4.
```rust
fn invalid_output() -> String {
String::from("foo")
@ -76,6 +80,7 @@ fn main() {}
```
5.
```rust
fn print_refs<'a, 'b>(x: &'a i32, y: &'b i32) {
println!("x is {} and y is {}", x, y);
@ -98,6 +103,7 @@ fn main() {
```
6.
```rust
// A type `Borrowed` which houses a reference to an
// `i32`. The reference to `i32` must outlive `Borrowed`.
@ -135,6 +141,7 @@ fn main() {
```
7. 🌟
```rust,editable
/* Make it work */
@ -165,8 +172,8 @@ fn main()
}
```
8. 🌟
```rust,editable
#[derive(Debug)]
@ -193,6 +200,7 @@ fn main()
```
9.
```rust
struct ImportantExcerpt<'a> {
part: &'a str,
@ -207,8 +215,8 @@ impl<'a> ImportantExcerpt<'a> {
fn main() {}
```
10.
```rust
fn nput(x: &i32) {

View File

@ -1,4 +1,5 @@
1、
```rust
fn main() {
let v: &str = "hello";
@ -26,6 +27,7 @@ fn need_static(r : &'static str) {
```
2、
```rust
#[derive(Debug)]
struct Config {
@ -54,6 +56,7 @@ fn main() {
```
3、
```rust
fn main() {
// Make a `string` literal and print it:
@ -65,6 +68,7 @@ fn main() {
```
5、
```rust
use std::fmt::Debug;

View File

@ -1,4 +1,5 @@
1.
```rust
struct Rectangle {
width: u32,
@ -19,6 +20,7 @@ fn main() {
```
2.
```rust
#[derive(Debug)]
struct TrafficLight {
@ -26,12 +28,13 @@ struct TrafficLight {
}
impl TrafficLight {
pub fn show_state(&self) {
pub fn show_state(&self) {
println!("the current state is {}", self.color);
}
}
fn main() {
let light = TrafficLight{
let light = TrafficLight {
color: "red".to_owned(),
};
// Don't take the ownership of `light` here
@ -42,6 +45,7 @@ fn main() {
```
3.
```rust
struct TrafficLight {
color: String,
@ -49,7 +53,7 @@ struct TrafficLight {
impl TrafficLight {
// using `Self` to fill in the blank
pub fn show_state(self: &Self) {
pub fn show_state(self: &Self) {
println!("the current state is {}", self.color);
}
@ -58,10 +62,12 @@ impl TrafficLight {
self.color = "green".to_string()
}
}
fn main() {}
```
4.
```rust
#[derive(Debug)]
struct TrafficLight {
@ -82,6 +88,7 @@ impl TrafficLight {
&self.color
}
}
fn main() {
let light = TrafficLight::new();
assert_eq!(light.get_state(), "red");
@ -89,6 +96,7 @@ fn main() {
```
5.
```rust
struct Rectangle {
width: u32,
@ -107,10 +115,12 @@ impl Rectangle {
self.width > other.width && self.height > other.height
}
}
fn main() {}
```
6.
```rust
#[derive(Debug)]
enum TrafficLightColor {
@ -135,6 +145,6 @@ fn main() {
assert_eq!(c.color(), "yellow");
println!("{:?}",c);
println!("{:?}", c);
}
```

View File

@ -1,4 +1,5 @@
1、
```rust
use std::fmt;
@ -17,6 +18,7 @@ fn main() {
```
2、
```rust
struct Meters(u32);
@ -30,6 +32,7 @@ fn main() {
```
3、
```rust
struct Years(i64);
@ -62,11 +65,13 @@ fn main() {
```
4、Sometimes `newtype` pattern can provide extra readability.
```rust
use std::ops::Add;
use std::fmt::{self, format};
struct Meters(u32);
impl fmt::Display for Meters {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "There are still {} meters left", self.0)
@ -80,9 +85,10 @@ impl Add for Meters {
Self(self.0 + other.0)
}
}
fn main() {
let d = calculate_distance(Meters(10), Meters(20));
assert_eq!(format!("{}",d), "There are still 30 meters left");
assert_eq!(format!("{}", d), "There are still 30 meters left");
}
/* implement calculate_distance */
@ -92,6 +98,7 @@ fn calculate_distance(d1: Meters, d2: Meters) -> Meters {
```
5、
```rust
enum VeryVerboseEnumOfThingsToDoWithNumbers {
Add,
@ -109,6 +116,7 @@ fn main() {
```
6、
```rust
enum VeryVerboseEnumOfThingsToDoWithNumbers {
Add,
@ -124,12 +132,11 @@ impl VeryVerboseEnumOfThingsToDoWithNumbers {
}
}
fn main() {
}
fn main() {}
```
7、
```rust
fn my_function<const N: usize>() -> [u32; N] {
[123; N]
@ -137,11 +144,12 @@ fn my_function<const N: usize>() -> [u32; N] {
fn main() {
let arr = my_function::<5>();
println!("{:?}",arr);
println!("{:?}", arr);
}
```
8、
```rust
fn main() {
let s: &str = "Hello there!";
@ -150,13 +158,14 @@ fn main() {
}
```
9、
```rust
use std::fmt::Display;
fn foobar_1(thing: &dyn Display) {}
fn foobar_2(thing: Box<dyn Display>) {}
fn main() {
}
fn foobar_1(thing: &dyn Display) {}
fn foobar_2(thing: Box<dyn Display>) {}
fn main() {}
```

View File

@ -1,4 +1,5 @@
1.
1.
```rust
fn main() {
let x = 5;
@ -9,7 +10,8 @@ fn main() {
}
```
2.
2.
```rust
fn main() {
let x = 5;
@ -20,7 +22,8 @@ fn main() {
}
```
3.
3.
```rust
fn main() {
let mut s = String::from("hello, ");
@ -31,7 +34,8 @@ fn main() {
fn borrow_object(s: &String) {}
```
4.
4.
```rust
fn main() {
let mut s = String::from("hello, ");
@ -44,7 +48,8 @@ fn push_str(s: &mut String) {
}
```
5.
5.
```rust
fn main() {
let mut s = String::from("hello, ");
@ -56,7 +61,8 @@ fn main() {
}
```
6.
6.
```rust
fn main() {
let c = '中';
@ -77,7 +83,8 @@ fn get_addr(r: &char) -> String {
}
```
7.
7.
```rust
fn main() {
let s = String::from("hello");
@ -89,7 +96,8 @@ fn main() {
}
```
8.
8.
```rust
fn main() {
//fix error by modifying this line
@ -101,7 +109,8 @@ fn main() {
fn borrow_object(s: &mut String) {}
```
9.
9.
```rust
fn main() {
let mut s = String::from("hello, ");
@ -114,7 +123,8 @@ fn main() {
fn borrow_object(s: &String) {}
```
10.
10.
```rust
fn main() {
let mut s = String::from("hello, ");
@ -128,7 +138,8 @@ fn main() {
}
```
11.
11.
```rust
fn main() {
let mut s = String::from("hello, ");

View File

@ -1,4 +1,5 @@
1.
```rust
fn main() {
let x = String::from("hello, world");
@ -32,6 +33,7 @@ fn main() {
```
2.
```rust
// Don't modify code in main!
fn main() {
@ -49,6 +51,7 @@ fn take_ownership(s: String) -> String {
```
3.
```rust
fn main() {
let s = give_ownership();
@ -78,6 +81,7 @@ fn give_ownership() -> String {
```
4.
```rust
fn main() {
let s = String::from("hello, world");
@ -93,6 +97,7 @@ fn print_str(s: String) {
```
5.
```rust
fn main() {
let x = (1, 2, (), "hello");
@ -102,6 +107,7 @@ fn main() {
```
6.
```rust
fn main() {
let s = String::from("hello, ");
@ -114,6 +120,7 @@ fn main() {
```
7.
```rust
fn main() {
let x = Box::new(5);
@ -127,6 +134,7 @@ fn main() {
```
8.
```rust
fn main() {
let t = (String::from("hello"), String::from("world"));
@ -139,6 +147,7 @@ fn main() {
```
9.
```rust
fn main() {
let t = (String::from("hello"), String::from("world"));

View File

@ -1,4 +1,5 @@
1.
```rust
enum Direction {
East,
@ -20,6 +21,7 @@ fn main() {
```
2.
```rust
fn main() {
let boolean = true;
@ -38,6 +40,7 @@ fn main() {
```
3.
```rust
enum Message {
Quit,
@ -74,6 +77,7 @@ fn show_message(msg: Message) {
```
4.
```rust
fn main() {
let alphabets = ['a', 'E', 'Z', '0', 'x', '9' , 'Y'];
@ -86,6 +90,7 @@ fn main() {
```
5.
```rust
enum MyEnum {
Foo,
@ -107,6 +112,7 @@ fn main() {
```
6.
```rust
fn main() {
let o = Some(7);
@ -118,6 +124,7 @@ fn main() {
```
7.
```rust
enum Foo {
Bar(u8)
@ -133,6 +140,7 @@ fn main() {
```
8.
```rust
enum Foo {
Bar,
@ -152,6 +160,7 @@ fn main() {
```
9.
```rust
fn main() {
let age = Some(30);

View File

@ -1,4 +1,5 @@
1.
```rust
fn main() {}
fn match_number(n: i32) {
@ -19,6 +20,7 @@ fn match_number(n: i32) {
```
2.
```rust
struct Point {
@ -40,6 +42,7 @@ fn main() {
```
3.
```rust
enum Message {
Hello { id: i32 },
@ -61,6 +64,7 @@ fn main() {
```
4.
```rust
fn main() {
let num = Some(4);
@ -74,6 +78,7 @@ fn main() {
```
5.
```rust
fn main() {
let numbers = (2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048);
@ -88,6 +93,7 @@ fn main() {
```
6.
```rust
fn main() {
let mut v = String::from("hello,");

View File

@ -1,4 +1,5 @@
1.
```rust
use core::panic;
@ -20,6 +21,7 @@ fn main() {
```
2.
```rust
// MAKE the code work by fixing all panics
fn main() {

View File

@ -1,4 +1,5 @@
1.
```rust
use std::num::ParseIntError;
@ -20,6 +21,7 @@ fn main() {
```
2.
```rust
use std::num::ParseIntError;
@ -38,6 +40,7 @@ fn main() {
```
3.
```rust
use std::fs::File;
use std::io::{self, Read};
@ -71,6 +74,7 @@ fn main() {
```
4.
```rust
use std::num::ParseIntError;
@ -100,6 +104,7 @@ fn main() {
```
5.
```rust
use std::num::ParseIntError;
@ -149,6 +154,7 @@ fn main() {
```
6.
```rust
use std::num::ParseIntError;

View File

@ -1,4 +1,5 @@
1.
```rust
fn main() {
let decimal = 97.123_f32;
@ -13,6 +14,7 @@ fn main() {
```
2.
```rust
// Suppress all warnings from casts which overflow.
#![allow(overflowing_literals)]
@ -24,6 +26,7 @@ fn main() {
```
3.
```rust
fn main() {
assert_eq!(1000 as u16, 1000);
@ -58,6 +61,7 @@ fn main() {
```
4.
```rust
fn main() {
let mut values: [i32; 2] = [1, 2];
@ -75,6 +79,7 @@ fn main() {
```
5.
```rust
fn main() {
let arr :[u64; 13] = [0; 13];

View File

@ -1,4 +1,5 @@
1.
```rust
fn main() {
// impl From<bool> for i32
@ -28,6 +29,7 @@ fn main() {
```
2.
```rust
// From is now included in `std::prelude`, so there is no need to introduce it into the current scope
// use std::convert::From;
@ -56,6 +58,7 @@ fn main() {
```
3.
```rust
use std::fs;
use std::io;
@ -92,6 +95,7 @@ fn main() {
```
4.
```rust
fn main() {
let n: i16 = 256;
@ -111,6 +115,7 @@ fn main() {
```
5.
```rust,editable
#[derive(Debug, PartialEq)]
struct EvenNum(i32);

View File

@ -1,4 +1,5 @@
1
```rust
use std::fmt;
@ -23,6 +24,7 @@ fn main() {
```
2.
```rust
// To use `from_str` method, you needs to introduce this trait into the current scope.
use std::str::FromStr;
@ -38,6 +40,7 @@ fn main() {
```
3.
```rust
use std::str::FromStr;
use std::num::ParseIntError;

View File

@ -1,23 +1,26 @@
1.
1.
```rust
fn main() {
let x: i32 = 5; // uninitialized but using, ERROR !
let y: i32; // uninitialized but also unusing, only warning
println!("{} is equal to 5", x);
println!("{} is equal to 5", x);
}
```
2.
```rust
fn main() {
let mut x = 1;
x += 2;
println!("{} is equal to 3", x);
let mut x = 1;
x += 2;
println!("{} is equal to 3", x);
}
```
3.
```rust
fn main() {
let x: i32 = 10;
@ -25,15 +28,16 @@ fn main() {
let y: i32 = 5;
println!("The value of x is {} and value of y is {}", x, y);
}
println!("The value of x is {}", x);
println!("The value of x is {}", x);
}
```
4.
```rust
fn main() {
let x = define_x();
println!("{}, world", x);
println!("{}, world", x);
}
fn define_x() -> String {
@ -45,7 +49,7 @@ fn define_x() -> String {
```rust
fn main() {
let x = define_x();
println!("{:?}, world", x);
println!("{:?}, world", x);
}
fn define_x() -> &'static str {
@ -55,6 +59,7 @@ fn define_x() -> &'static str {
```
5.
```rust
fn main() {
let x: i32 = 5;
@ -65,42 +70,45 @@ fn main() {
assert_eq!(x, 5);
let x = 42;
let x = 42;
println!("{}", x); // Prints "42".
}
```
6.
```rust
fn main() {
let mut x: i32 = 1;
x = 7;
// shadowing and re-binding
let x = x;
let x = x;
// x += 3;
let y = 4;
// shadowing
let y = "I can also be bound to text!";
let y = "I can also be bound to text!";
}
```
7.
```rust
fn main() {
let _x = 1;
let _x = 1;
}
```
```rust
#[allow(unused_variables)]
fn main() {
let x = 1;
let x = 1;
}
```
8.
```rust
fn main() {
let (mut x, y) = (1, 2);
@ -122,12 +130,13 @@ fn main() {
```
9.
```rust
fn main() {
let (x, y);
(x,..) = (3, 4);
(x, ..) = (3, 4);
[.., y] = [1, 2];
// fill the blank to make the code work
assert_eq!([x,y], [3,2]);
assert_eq!([x, y], [3, 2]);
}
```