【Rust】構造体(struct)の要素にvector

#[derive(Debug, Serialize, Clone, Deserialize)]
struct Name {
    family: String,
    first: String,
    age: u32,
    hobby: Vec<String>,
}

fn main(){
    let n1 = Name {family: "yamada".to_string(), first: "taro".to_string(), age: 20, hobby: vec!["サッカー".to_string(), "旅行".to_string()]};

    println!("{:?}", n1);
}

$ cargo run
Compiling sample v0.1.0 (/home/vagrant/dev/rust/sample)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.34s
Running `target/debug/sample`
Name { family: “yamada”, first: “taro”, age: 20, hobby: [“サッカー”, “旅行”] }

VecのところをVec<(構造体名)>でもできる。ちょっとややこしいけど…

use serde::{Serialize, Deserialize};
use once_cell::sync::Lazy;
use std::sync::Mutex;
use std::ops::DerefMut;


#[derive(Debug, Serialize, Clone, Deserialize)]
struct Name {
    family: String,
    first: String,
    age: u32,
    note: String,
}

#[derive(Debug, Serialize, Clone, Deserialize)]
struct list {
    family: String,
    first: String,
    age: u32,
    note: Vec<Name>,
}

static VECT: Lazy<Mutex<Vec<Name>>> = Lazy::new(|| Mutex::new(vec![]));

fn push_name() {
    let n1 = Name {family: "yamada".to_string(), first: "taro".to_string(), age: 20, note: "AAA".to_string()};
    VECT.lock().unwrap().push(n1);
    let n2 = Name {family: "tanaka".to_string(), first: "kazuo".to_string(), age: 18, note: "BBB".to_string()};
    VECT.lock().unwrap().push(n2);
    let n3 = Name {family: "sato".to_string(), first: "hanako".to_string(), age: 22, note: "CCC".to_string()};
    VECT.lock().unwrap().push(n3);
}

fn main(){
    push_name();

    let mut binding = VECT.lock().unwrap();
    let objs = binding.deref_mut();

    let l1 = list {family: "yamada".to_string(), first: "taro".to_string(), age: 20, note: objs.to_vec()};

    println!("{:?}", l1);
}

$ cargo run
Compiling sample v0.1.0 (/home/vagrant/dev/rust/sample)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.28s
Running `target/debug/sample`
Name2 { family: “yamada”, first: “taro”, age: 20, note: [Name { family: “yamada”, first: “taro”, age: 20, note: “AAA” }, Name { family: “tanaka”, first: “kazuo”, age: 18, note: “BBB” }, Name { family: “sato”, first: “hanako”, age: 22, note: “CCC” }] }

うむ、普通に出来ますね。これをマイニング終了のタイミングでBlockとトランザクションで作りたい。

use serde::{Serialize, Deserialize};

#[derive(Debug, Serialize, Clone, Deserialize)]
struct Block {
    time: String,
    transactions: Vec<String>,
    hash: String,
    nonce: String,
}

fn main(){
    let t = vec!["sender".to_string(), "receiver".to_string(), "amount".to_string()];
    let b = Block{time:"a".to_string(), transactions: t, hash:"aaa".to_string(), nonce:"aaa".to_string()};
    println!("{:?}", b);
}

$ cargo run
Compiling sample v0.1.0 (/home/vagrant/dev/rust/sample)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.31s
Running `target/debug/sample`
Block { time: “a”, transactions: [“sender”, “receiver”, “amount”], hash: “aaa”, nonce: “aaa” }

これを作っていきます!