You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Scrypto中如何从自定义文件夹向script.rs导入Date结构体?

在Scrypto中跨文件使用自定义Date结构体的步骤

要在script.rs中使用custom_types/type.rs里定义的Date结构体,需遵循Rust的模块导出与导入规则,具体操作如下:

1. 确认结构体的公开权限

你的type.rs中已将Date标记为pub,这一步符合外部访问要求,无需修改:

use sbor::*;

#[derive(TypeId, Encode, Decode, Describe)]
pub struct Date {
    year: u8,
    day: u8,
    month: u8,
}

2. 导出custom_types模块到库根目录

因为script.rs属于同一 crate 下的文件,需要通过lib.rs将custom_types模块公开:

  • 在custom_types文件夹下创建mod.rs文件,内容为:
// type是Rust关键字,需用r#type引用模块
pub mod r#type;
  • 在lib.rs中添加模块声明:
pub mod custom_types;

3. 在script.rs中导入并使用Date

在script.rs开头添加导入语句,之后即可直接使用Date结构体:

use crate::custom_types::r#type::Date;

// 示例使用
fn main() {
    let birthday = Date {
        year: 2020,
        month: 5,
        day: 20,
    };
    // 执行你的Scrypto脚本逻辑
}

可选优化:避免关键字冲突

由于type是Rust保留关键字,引用时需加r#前缀较为繁琐。建议将type.rs重命名为date.rs,简化模块引用:

  • 重命名文件后,修改custom_types/mod.rs为:
pub mod date;
  • 在script.rs中导入:
use crate::custom_types::date::Date;

内容的提问来源于stack exchange,提问作者M80

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 21:48:19