Open8

Sandbox For Rust

Yuta OhiraYuta Ohira

Rustの環境構築(asdf)

$ asdf plugin-add rust
$ asdf install rust latest
$ asdf global rust latest
$ rustup --version
rustup 1.24.3 (ce5817a94 2021-05-31)
info: This is the version for the rustup toolchain manager, not the rustc compiler.
info: The currently active `rustc` version is `rustc 1.61.0 (fe5b13d68 2022-05-18)`

https://github.com/asdf-community/asdf-rust

Yuta OhiraYuta Ohira

Rustup: the Rust toolchain installer

$ rustup --version
rustup 1.24.3 (ce5817a94 2021-05-31)
info: This is the version for the rustup toolchain manager, not the rustc compiler.
info: The currently active `rustc` version is `rustc 1.61.0 (fe5b13d68 2022-05-18)`

https://github.com/rust-lang/rustup

Cargo

$ cargo --version
cargo 1.61.0 (a028ae42f 2022-04-29)

https://tomoyuki-nakabayashi.github.io/embedded-rust-techniques/04-tools/cargo.html
https://github.com/rust-lang/cargo

rustc

$ rustc --version
rustc 1.61.0 (fe5b13d68 2022-05-18)

https://tomoyuki-nakabayashi.github.io/embedded-rust-techniques/04-tools/rustc.html

Yuta OhiraYuta Ohira

rustプロジェクトを作成する

$ cargo new rust-sample
$ ls rust-sample
$ tree
.
├── Cargo.toml
└── src
    └── main.rs

1 directory, 2 files

実行

$ cargo run
   Compiling rust-sample v0.1.0 (/Users/yutaohira/work/prog/rust-sample)
    Finished dev [unoptimized + debuginfo] target(s) in 0.50s
     Running `target/debug/rust-sample`
Hello, world!
Yuta OhiraYuta Ohira

Rust Language Serverを導入

$ rustup component add rls rust-analysis rust-src
Yuta OhiraYuta Ohira

非同期ランタイム

futures

cargo add futures
main.rs
use futures::executor;

fn main() {
    executor::block_on(async_add_logger(2, 3));
}

async fn async_add(left: i32, right: i32) -> i32 {
    return left + right;
}

async fn async_add_logger(left: i32, right: i32) {
    let result = async_add(left, right).await;
    println!("{} + {} = {}", left, right, result);
}

tokio

https://tokio.rs/

cargo.toml
[dependencies]
tokio = { version = "1.19.2", features = ["macros", "rt", "rt-multi-thread"] }
main.rs
#[tokio::main]
async fn main() {
  async_add_logger(2, 3).await;
}

/** 非同期足し算 */
async fn async_add(left: i32, right: i32) -> i32 {
    return left + right;
}

/** 非同期足し算 ログを出力 */
async fn async_add_logger(left: i32, right: i32) {
    let result = async_add(left, right).await;
    println!("{} + {} = {}", left, right, result);
}

async-std

https://async.rs/

cargo.toml
[dependencies]
async-std = { version = "1.11.0", features = ["attributes"] }
main.rs
#[async_std::main]
async fn main() {
  async_add_logger(2, 8).await;
}

/** 非同期足し算 */
async fn async_add(left: i32, right: i32) -> i32 {
    return left + right;
}

/** 非同期足し算 ログを出力 */
async fn async_add_logger(left: i32, right: i32) {
    let result = async_add(left, right).await;
    println!("{} + {} = {}", left, right, result);
}