对象包装 vs 非对象结构体

在之前的课程中,我们学习了对象包装,以及如何将一个 SuiFren 对象包装成 GiftBox:

public struct GiftBox has key {
    id: UID,
    inner: SuiFren,
}

entry fun wrap_fren(fren: SuiFren, ctx: &mut TxContext) {
    let gift_box = GiftBox {
        id: object::new(ctx),
        inner: fren,
    };
    transfer::transfer(gift_box, tx_context::sender(ctx));
}

还有一种具有类似的语法能替代对象包装的方法 —— 使用仅具有 store 能力的非对象结构体:

public struct SuiFren has store {
    generation: u64,
    birthdate: u64,
    attributes: vector<String>,
}

这种方法通常只有在开发人员不打算将嵌套结构体类型转变为对象时才有用。这可以帮助将一个长的对象结构体分解成较小的相关组件,例如:

public struct LongObject has key {
    id: UID,
    field_1: u64,
    field_2: u64,
    field_3: u64,
    field_4: u64,
    field_5: u64,
    field_6: u64,
    field_7: u64,
    field_8: u64,
}

对比

public struct BigObject has key {
    id: UID,
    field_group_1: FieldGroup1,
    field_group_2: FieldGroup2,
    field_group_3: FieldGroup3,
}

public struct FieldGroup1 has store {
    field_1: u64,
    field_2: u64,
    field_3: u64,
}

public struct FieldGroup2 has store {
    field_4: u64,
    field_5: u64,
    field_6: u64,
}

public struct FieldGroup3 has store {
    field_7: u64,
    field_8: u64,

}