Rustでも標準で誰もが使うものが用意されている。ライブラリに相当するものをクレート(crate)と呼ぶことがある
基本的なstdにはプリミティブなデータ型やモジュール、マクロなどが定義されている
crates.ioにたくさんのパッケージがある
let f:f64 = 3.45;
let val = f.sqrt();
use std::f64; fn main() { let f:f64 = 3.45; println!("{}の平方根={:?}", f, f.sqrt()); }
fn main() { let s = "hello, dogs"; println!("{:?}", s.to_uppercase()); }
乱数はRngというトレイトを使うことができる
use rand::Rng; fn main() { let mut r = rand::thread_rng(); for _i in 1..6 { println!("{}", r.gen_range(1, 11)); } }
### クレートを使うプロジェクト
クレートの最新バージョンを調べる
$ cargo search rand
Updating crates.io index
rand = “0.8.5” # Random number generators and other randomness functionality.
tinyrand = “0.5.0” # Lightweight RNG specification and several ultrafast implementations in Rust.
bevy_rand = “0.1.0” # A plugin to integrate rand for ECS optimised RNG for the Bevy game engine.
random_derive = “0.0.0” # Procedurally defined macro for automatically deriving rand::Rand for structs and enums
faker_rand = “0.1.1” # Fake data generators for lorem ipsum, names, emails, and more
rand_derive2 = “0.1.21” # Generate customizable random types with the rand crate
fake-rand-test = “0.0.0” # Random number generators and other randomness functionality.
ndarray-rand = “0.14.0” # Constructors for randomized arrays. `rand` integration for `ndarray`.
rand_derive = “0.5.0” # `#[derive(Rand)]` macro (deprecated).
rand_core = “0.6.4” # Core random number generator traits and tools for implementation.
… and 1126 crates more (use –limit N to see more)
$ cargo new random3 –bin
Created binary (application) `random3` package
実数の数値計算
abs(), acos(), asin(), atan(), ceil(), copisign(), cos(), exp(), exp2(), floor(), fract(), ln(), log(), log10(), log2(), mul_add(), powf(), powi(), round(), signum(), sin(), sqrt(), tan(), trunc()
use std::f64; fn main() { let f:f64 = 3.45; println!("{:?}", f.fract()); }
文字列の操作
find(), matches(), parse(), repeat(), to_lowercase(), to_uppercase(), trim(), trim_end(), trim_start()
乱数の生成
gen(), gen_range(), gen_bool(), gen_ratio(2, 3)
use rand::{thread_rng, Rng}; fn main() { let mut rng = thread_rng(); for _ in 0..11 { let x: u16 = rng.gen(); print!("{} ", x); } }
use rand::{thread_rng, Rng}; fn main() { let mut rng = thread_rng(); for _ in 0..11 { let x: u16 = rng.gen_range(0, 3); print!("{} ", x); } }
### 日付日時
Date, DateTime, Duration
use chrono::{Utc, Local, DateTime}; use chrono::{Datelike, Timelike}; fn main() { let utc: DateTime<Utc> = Utc::now(); println!("{}", utc); let local: DateTime<Local> = Local::now(); println!("{}", local); println!("{}/{}/{}", local.year(), local.month(), local.day()); println!("{:02}:{:02}:{:02}", local.hour(), local.minute(), local.second()); }
use std::thread; use std::time::Duration; fn main() { println!("3秒待ちます。"); thread::sleep(Duration::from_secs(3)); println!("3秒待ちました"); }