Rustで構造体を定義する - kossy0701/walk-the-dog GitHub Wiki

入門

  1. 定義
struct Book {
    title: String,
    author: String,
    publication_year: i32,
    isbn: String,
}
  1. 定義した構造体の変数を作成する
let book = Book {
    title: "RustWebAssemblyによるゲーム開発".to_string(),
    author: "Eric Smith".to_string(),
    publication_year: 2023,
    isbn: "123-4-56789-123-4".to_string(),
};
  1. 構造体にアノテーションする
# cargo.toml
[dependencies]
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"

# main.rs
use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize)]
struct Book {
    title: String,
    author: String,
    publication_year: i32,
    isbn: String,
}
  • JSONへシリアライズする
use serde::{Serialize, Deserialize};
use serde_json;

#[derive(Serialize, Deserialize, Debug)]
struct Book {
    title: String,
    author: String,
    publication_year: i32,
    isbn: String,
}

fn main() {
    let book = Book {
        title: "RustWebAssemblyによるゲーム開発".to_string(),
        author: "Eric Smith".to_string(),
        publication_year: 2023,
        isbn: "123-4-56789-123-4".to_string(),
    };

    // BookをJSON文字列にシリアル化
    let serialized_book = serde_json::to_string(&book).unwrap();
    println!("Serialized Book: {}", serialized_book);
}
  • JSONからデシリアライズする
use serde::{Serialize, Deserialize};
use serde_json;

#[derive(Serialize, Deserialize, Debug)]
struct Book {
    title: String,
    author: String,
    publication_year: i32,
    isbn: String,
}

fn main() {
    let serialized_book = r#"{
        "title": "RustWebAssemblyによるゲーム開発",
        "author": "Eric Smith",
        "publication_year": 2023,
        "isbn": "123-4-56789-123-4"
    }"#;

    // JSON文字列をBookにデシリアル化
    let deserialized_book: Book = serde_json::from_str(&serialized_book).unwrap();
    println!("Deserialized Book: {:?}", deserialized_book);
}