### トランザクション
use std::collections::HashMap; fn main(){ let transaction = HashMap::from([ ("Time", "2024-12-20 13:58"), ("sender", "A"), ("receiver", "B"), ("amount", "1") ]); for (k, v) in &transaction { println!("{} {}", k, v); } }
Hashmapだとkey, valueが全て同じ型になってしまうので、構造体を使用する。
#[derive(Debug)] struct Transaction { time: String, sender: String, receiver: String, amount: i32, } fn main(){ let t1 = Transaction {time: "2024-12-20 13:58".to_string(), sender: "A".to_string(), receiver: "B".to_string(), amount: 10}; println!("{:?}", t1); }
$ ./main
Transaction { time: “2024-12-20 13:58”, sender: “A”, receiver: “B”, amount: 10 }
複数トランザクションの場合は配列を使用する
fn main(){ let t1 = Transaction {time: "2024-12-20 13:58".to_string(), sender: "A".to_string(), receiver: "B".to_string(), amount: 10}; let t2 = Transaction {time: "2024-12-21 13:58".to_string(), sender: "B".to_string(), receiver: "C".to_string(), amount: 5}; let transactions = [t1, t2]; println!("{:?}", transactions); }
### Rustで日時を扱う
use chrono::{Utc, Local, DateTime, Date}; fn main(){ let utc_datetime: DateTime<Utc> = Utc::now(); let utc_date: Date<Utc> = Utc::today(); println!("{}", utc_datetime); println!("{}", utc_date); }
2024-12-20 05:46:43.775637762 UTC
2024-12-20UTC
crateを使うには、Cargo.tomlを利用する
[package] name = "hoge" version = "0.1.0" edition = "2021" [dependencies] chrono = "0.4.23"
凄い基本的なことを書くだけでも時間がかかりますな。。
use chrono::{Utc, Local, DateTime, Date}; #[derive(Debug)] struct Transaction { time: String, sender: String, receiver: String, amount: i32, } fn main(){ let utc_datetime: DateTime<Utc> = Utc::now(); let t1 = Transaction {time: utc_datetime.to_string(), sender: "A".to_string(), receiver: "B".to_string(), amount: 10}; let t2 = Transaction {time: utc_datetime.to_string(), sender: "B".to_string(), receiver: "C".to_string(), amount: 5}; let transactions = [t1, t2]; println!("{:?}", transactions); }
[Transaction { time: “2024-12-21 06:09:35.567867379 UTC”, sender: “A”, receiver: “B”, amount: 10 }, Transaction { time: “2024-12-21 06:09:35.567867379 UTC”, sender: “B”, receiver: “C”, amount: 5 }]