Skip to content

Instantly share code, notes, and snippets.

@redink
Created April 13, 2019 03:17
Show Gist options
  • Save redink/146d98908d8305e048cc9f27d30cb22a to your computer and use it in GitHub Desktop.
Save redink/146d98908d8305e048cc9f27d30cb22a to your computer and use it in GitHub Desktop.
chapter 2 code example
use std::collections::VecDeque;
use std::collections::BTreeMap;
use std::fmt::Debug;
fn main() {
answer();
transfer_ownership();
ref_example();
fn_example();
scope_example();
fn_pointer();
closure_example();
closure_as_param();
match_example();
if_let();
while_let();
tuple_example();
struct_example();
tuple_struct_example();
enum_example(Number::Two);
vec_example();
vec_deque_example();
kv_example();
option_example();
trait_example();
}
#[derive(Copy, Clone)]
struct Duck;
struct Pig;
trait Fly {
fn fly(&self) -> bool;
}
impl Fly for Duck {
fn fly(&self) -> bool {
return true;
}
}
fn fly_static<T: Fly>(s: T) -> bool {
s.fly()
}
fn trait_example() -> () {
let duck = Duck;
assert_eq!(true, duck.fly());
assert_eq!(true, fly_static::<Duck>(duck));
assert_eq!(true, fly_static(duck));
}
fn match_option<T: Debug>(o: Option<T>) {
match o {
Some(i) => println!("{:?}", i),
None => println!("nothing"),
}
}
fn option_example() -> () {
let a = Some(3);
let b = Some("hello");
let c = Some(Number::One);
match_option(a);
match_option(b);
// match_option(c);
// |
// 40 | match_option(c);
// | ^^^^^^^^^^^^ `Number` cannot be formatted using `{:?}`
// |
// = help: the trait `std::fmt::Debug` is not implemented for `Number`
}
fn kv_example() -> () {
let mut bmap = BTreeMap::new();
bmap.insert("key1", 1);
bmap.insert("key2", 2);
println!(":::::: {:?}", bmap);
}
fn vec_deque_example() -> () {
let mut vd = VecDeque::new();
vd.push_front(1);
vd.push_front(2);
println!(".... {:?}", vd);
// assert_eq!(2, vd.get(0));
// no implementation for `{integer} == std::option::Option<&{integer}>`
assert_eq!(Some(&2), vd.get(0));
}
fn vec_example() -> () {
let mut v = vec![];
v.push(1);
// v.push("2");
v.push(2);
println!("... {:?}.... {:?}", v[0], v);
}
//#[derive(Debug)]
enum Number {
Zero,
One,
Two,
}
fn enum_example(a: Number) -> () {
match a {
Number::Zero => println!("0"),
Number::One => println!("1"),
Number::Two => println!("2"),
}
}
struct Color(i32, i32, i32);
fn tuple_struct_example() -> () {
let c = Color(1, 1,1);
assert_eq!(1, c.0);
assert_eq!(1, c.1);
assert_eq!(1, c.2);
}
#[derive(Debug)]
struct People {
name: &'static str,
gender: u32,
}
impl People {
fn new(name: &'static str, gender: u32) -> People {
// People{name: name, gender: gender}
People{name, gender}
}
fn name(&self) -> &'static str {
self.name
}
fn set_name(&mut self, name: &'static str) {
self.name = name;
}
fn gender(&self) -> u32 {
self.gender
}
}
fn struct_example() -> () {
let name: &'static str = "redink";
let gender: u32 = 18;
let mut people = People::new(name, gender);
println!("the name of people is: {:?}", people.name());
println!("the gender of people is: {:?}", people.gender());
people.set_name("new redink");
println!("the new name of people is: {:?}", people.name());
}
fn tuple_example() -> () {
let tuple: (&'static str, i32, char) = ("hello", 5, 'c');
assert_eq!("hello", tuple.0);
assert_eq!(5, tuple.1);
let coords = (1, 2);
let new_coords = move_coords(coords);
let (x, y) = new_coords;
assert_eq!(2, x);
assert_eq!(3, y);
fn move_coords(tuple: (i32, i32)) -> (i32, i32) {
(tuple.0 + 1, tuple.1 + 1)
}
}
fn if_let() -> () {
let boolean = true;
let mut binary = 0;
if let true = boolean {
binary = 1;
}
assert_eq!(1, binary);
}
fn while_let() -> () {
let mut v = vec![1,2,3,4];
while let Some(x) = v.pop() {
println!("{}", x);
}
}
fn match_example() -> () {
let n = 42;
match n {
o @ 42 => println!("n: {:?}", o),
_ => println!("common"),
// match 的通配是必须的吗?即使是这样
}
}
fn closure_as_param() -> () {
let a = 2;
let b = 3;
assert_eq!(5, closure_as_param_math(|| a + b));
assert_eq!(6, closure_as_param_math(|| a * b ));
}
fn closure_as_param_math<F: Fn() -> i32>(op: F) -> i32 {
op()
}
fn closure_example() -> () {
let out = 42;
fn add(i: i32, j: i32) -> i32 {
i + j
};
let closure_an = |i: i32, j: i32| -> i32 {
i + j + out
};
let a = 1;
let b = 2;
assert_eq!(3, add(a, b));
assert_eq!(45, closure_an(a, b));
}
fn fn_pointer() -> () {
let a = 2;
let b = 3;
// op 直接用函数名就可以
assert_eq!(5, math(sumsum, a, b));
assert_eq!(6, math(product, a, b));
}
fn math(op: fn(i32, i32) -> i32, a: i32, b: i32) -> i32 {
op(a, b)
}
fn sumsum(a: i32, b: i32) -> i32 {
a + b
}
fn product(a: i32, b: i32) -> i32 {
a * b
}
fn scope_example() -> () {
let v = "hello world";
assert_eq!("hello world", v);
{
let v = "hello rust";
assert_eq!("hello rust", v);
}
assert_eq!("hello world", v);
}
fn fizz_buzz(n: i32) -> String {
if n % 15 == 0 {
return "fizz_buzz".to_string();
} else if n% 3 == 0 {
return "fizz".to_string();
} else if n % 5 == 0 {
return "buzz".to_string();
} else {
return n.to_string();
}
}
fn fn_example() -> () {
assert_eq!(fizz_buzz(15), "fizz_buzz".to_string());
}
pub fn answer() -> () {
let a = 40;
let b = 20 ;
assert_eq!(sum(a, b), 60);
}
pub fn sum(a: i32, b: i32) -> i32 {
a + b
}
//
fn transfer_ownership() -> () {
let p1 = "hello";
let p2 = p1.to_string();
let other = p1;
println!("{:?}", other);
println!("{:?}", p1);
let other = p2;
println!("{:?}", other);
// println!("{:?}", p2);
}
fn ref_example() -> () {
let a = [1,2,3];
let b = &a;
// 获得内存地址
println!("the address of the b is {:p}", b);
let mut c = vec![1,2,3];
let d = &mut c;
d.push(4);
println!("the new vec is: {:?}", c);
let e = &42;
assert_eq!(42, *e);
// *e 表示解引用
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment