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

Motoko入门求助:如何向可变数组Posts中推送对象?

解决Motoko可变数组推送对象的错误

你的代码问题出在addPost函数里的push调用:Motoko数组的push方法仅接受单个元素作为参数,而你直接传入了id和creater两个原始值,这不符合Post类型的定义要求。

你需要先创建一个符合Post类型的对象,再将这个对象推入数组。修正后的代码如下:

actor {
  type Post = {
    id : Int;
    creater : String;
  };

  stable var Posts : [Post] = [];

  func addPost(id : Int, creater : String) : () {
    // 创建符合Post类型的对象,利用字段名与变量名相同的简写语法
    Posts.push({ id; creater });
  };
};

如果不习惯简写,也可以显式写出字段赋值:

func addPost(id : Int, creater : String) : () {
  let newPost : Post = { id = id; creater = creater };
  Posts.push(newPost);
};

这样就能正确向Posts数组中添加Post对象了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 10:35:19