rust 代码从Rust Playground共享

代码从Rust Playground共享

playground.rs
use std::convert::From;

#[derive(Debug)]
struct Number {
    value: i32,
}

impl From<i32> for Number {
    fn from(item: i32) -> Self {
        Number { value: item }
    }
}

fn main() {
    let num = Number::from(30);
    println!("My number is {:?}", num);
}

rust 代码从Rust Playground共享

代码从Rust Playground共享

playground.rs
fn main() {
    println!("Hello, world!");
}

rust 代码从Rust Playground共享

代码从Rust Playground共享

README.md
https://doc.rust-lang.org/book/ch16-02-message-passing.html#using-message-passing-to-transfer-data-between-threads

> We’ve used recv in this example for simplicity; we don’t have any other work for the main thread to do other than wait for messages, so blocking the main thread is appropriate.

Then I have a try to implement it with `try_recv`.
playground.rs
use std::thread;
use std::sync::mpsc;
use std::time;

fn main() {
    let (tx, rx) = mpsc::channel();

    thread::spawn(move || {
        let val = String::from("hi");
        thread::sleep(time::Duration::from_millis(100));
        tx.send(val).unwrap();
    });

    loop {
        match rx.try_recv() {
            Ok(r) => {
                println!("Got: {}", r);
                break;
                
            },
            Err(err) => {
                println!("Waiting...");
                thread::sleep(time::Duration::from_millis(10));
            }
        }
    }
}

rust grid.rs

grid.rs
use std::usize;

pub struct Grid {
    pub width: usize,
    pub height: usize,
    tiles: Vec<char>
}

impl Grid {
    pub fn new(width: usize, height: usize) -> Grid {
        let mut tiles = Vec::new();
        for _i in 0..(width * height) {
            tiles.push('.');
        }

        Grid {
            width,
            height,
            tiles
        }
    }

    pub fn _get(&self, x: usize, y: usize) -> char {
        return self.tiles[self.width * y + x];
    }

    pub fn set(&mut self, value: char, x: usize, y: usize) {
        self.tiles[self.width * y + x] = value;
    }

    pub fn for_each(&mut self, callback: fn()) {
        for _i in 0..(self.width * self.height) {
            // let x = 0;
            // let y = _i / self.width;
            callback();
        }
    }

    pub fn print(&self) {
        for i in 0..self.tiles.len() {
            if i % self.width as usize == 0 {
                print!("\n");
            }
            print!("{}", self.tiles[i]);
            print!(" ");
        }
        print!("\n");
    }
}

rust 生锈网格

生锈网格

grid.rs
use std::usize;

pub struct Grid {
    pub width: usize,
    pub height: usize,
    tiles: Vec<char>
}

impl Grid {
    pub fn new(width: usize, height: usize) -> Grid {
        let mut tiles = Vec::new();
        for _i in 0..(width * height) {
            tiles.push('.');
        }

        Grid {
            width,
            height,
            tiles
        }
    }

    pub fn _get(&self, x: usize, y: usize) -> char {
        return self.tiles[self.width * y + x];
    }

    pub fn set(&mut self, value: char, x: usize, y: usize) {
        self.tiles[self.width * y + x] = value;
    }

    pub fn for_each(&mut self, callback: fn()) {
        for _i in 0..(self.width * self.height) {
            // let x = 0;
            // let y = _i / self.width;
            callback();
        }
    }

    pub fn print(&self) {
        for i in 0..self.tiles.len() {
            if i % self.width as usize == 0 {
                print!("\n");
            }
            print!("{}", self.tiles[i]);
            print!(" ");
        }
        print!("\n");
    }
}

rust Rust envconfig示例

Rust envconfig示例

Cargo.toml
[package]
name = "rust-envconfig-sample"
version = "0.1.0"
authors = ["Yutaka Yawata"]
edition = "2018"

[dependencies]
envconfig = "0.5.0"
envconfig_derive = "0.5.0"
main.rs
use envconfig_derive::Envconfig;
use envconfig::Envconfig;
use std::process;

#[derive(Envconfig, Debug)]
struct Config {
    #[envconfig(from = "HOST")]
    host: String,
    #[envconfig(from = "PORT", default = "8080")]
    port: u16,
}

fn main() {
    // HOST=myserver
    // PORT=8080

    let config = match Config::init() {
        Ok(val) => val,
        Err(err) => {
            println!("{}",err);
            process::exit(1);
        }
    };

    println!("{:#?}", config);

    assert_eq!(config.host, "myserver");
    assert_eq!(config.port, 8080);
}

rust Rust envy example3

Rust envy example3

main.rs
use serde_derive::Deserialize;
use envy;
use std::error::Error;

#[derive(Deserialize, Debug)]
struct Config {
    host: String,
    #[serde(default="default_port")]
    port: u16,
    numbers: Vec<u64>,
}

fn default_port() -> u16 {
    8080
}

fn main() {
    // HOST=myserver
    // NUMBERS=1,2,3

    let config = match envy::from_env::<Config>() {
        Ok(val) => val,
        Err(err) => {
            println!("{}", err);
            process::exit(1);
        }
    };

    println!("{:#?}", config);

    assert_eq!(config.host, "myserver");
    assert_eq!(config.port, 8080);
    assert_eq!(config.numbers, vec![1,2,3]);

}

rust Rust envy example2

Rust envy example2

main.rs
use serde_derive::Deserialize;
use envy;
use std::process;

#[derive(Deserialize, Debug)]
struct Config {
    host: String,
    port: Option<u16>,
    numbers: Vec<u64>,
}

fn main() {
    // APP_HOST=myserver
    // PORT=8080
    // APP_NUMBERS=1,2,3

    let config = match envy::prefixed("APP_").from_env::<Config>() {
        Ok(val) => val,
        Err(err) => {
            println!("{}", err);
            process::exit(1);
        }
    };

    println!("{:#?}", config);

    assert_eq!(config.host, "myserver");
    assert_eq!(config.port, None);
    assert_eq!(config.numbers, vec![1,2,3]);
}

rust Rust envy example1

Rust envy example1

Cargo.toml
[package]
name = "rust-envy-sample"
version = "0.1.0"
authors = ["Yutaka Yawata"]
edition = "2018"

[dependencies]
envy = "0.3.3"
serde = "1.0.87"
serde_derive = "1.0.87"
main.rs
use serde_derive::Deserialize;
use envy;
use std::error::Error;

#[derive(Deserialize, Debug)]
struct Config {
    host: String,
    port: Option<u16>,
    numbers: Vec<u64>,
}

fn main() {
    // HOST=myserver
    // PORT=8080
    // NUMBERS=1,2,3

    let config = match envy::from_env::<Config>() {
        Ok(val) => val,
        Err(err) => {
            println!("{}", err);
            process::exit(1);
        }
    };

    println!("{:#?}", config);

    assert_eq!(config.host, "myserver");
    assert_eq!(config.port, Some(8080));
    assert_eq!(config.numbers, vec![1,2,3]);
}

rust Rust std :: env示例

Rust std :: env示例

main.rs
use std::env;
use std::process;

fn main() {
    // HOST=myserver
    // PORT=8080
    let host_key = "HOST";
    let port_key = "PORT";
    let default_port = 8080;

    let host = match env::var(host_key) {
        Ok(val) => val,
        Err(err) => {
            println!("{}: {}", err, host_key);
            process::exit(1);
        },
    };

    let port = match env::var(port_key) {
        Ok(val) => match val.parse::<u16>() {
            Ok(port) => port,
            Err(_) => {
                println!(
                    "the port number \"{}\" is invalid. default port will be used.",
                    val
                );
                default_port
            }
        },
        Err(_) => {
            println!(
                "\"{}\" is not defined in environment variables. default port will be used.",
                port_key
            );
            default_port
        }
    };

    assert_eq!(port, 8080);
    assert_eq!(host, "myserver");
}