問題一覧に戻る
中級Move開発
問題 24: アクセサ関数

Moveにおけるアクセサ関数について学びます。これらの関数を使用すると、他のモジュールがあなたのモジュールの構造体フィールドを読み取ることができます。構造体フィールドはデフォルトでプライベートなので、アクセサ関数は特定のフィールドへの読み取り専用アクセスを制御された方法で提供します。

module my_first_package::example;

// Part 1: These imports are provided by default
// use sui::object::{Self, UID};
// use sui::transfer;
// use sui::tx_context::{Self, TxContext};

// Part 2: struct definitions
public struct Sword has key, store {
id: UID,
magic: u64,
strength: u64,
}

public struct Forge has key {
id: UID,
swords_created: u64,
}

// Part 3: Module initializer to be executed when this module is published
fun init(ctx: &mut TxContext) {
let admin = Forge {
id: object::new(ctx),
swords_created: 0,
};

// Transfer the forge object to the module/package publisher
transfer::transfer(admin, ctx.sender());
}

// Part 4: Accessors required to read the struct fields
// Swordのmagicフィールドを読み取るアクセサ
public fun magic(: ): u64 {
.magic
}

// Swordのstrengthフィールドを読み取るアクセサ
public fun strength(: ): u64 {
.strength
}

// Forgeのswords_createdフィールドを読み取るアクセサ
public fun swords_created(: ): u64 {
.swords_created
}