惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

阮一峰的网络日志
阮一峰的网络日志
Blog — PlanetScale
Blog — PlanetScale
B
Blog RSS Feed
L
LangChain Blog
Jina AI
Jina AI
爱范儿
爱范儿
C
Check Point Blog
云风的 BLOG
云风的 BLOG
Last Week in AI
Last Week in AI
月光博客
月光博客
GbyAI
GbyAI
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Stack Overflow Blog
Stack Overflow Blog
V
V2EX
A
About on SuperTechFans
有赞技术团队
有赞技术团队
Microsoft Azure Blog
Microsoft Azure Blog
The GitHub Blog
The GitHub Blog
博客园 - Franky
Apple Machine Learning Research
Apple Machine Learning Research
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Google DeepMind News
Google DeepMind News
博客园 - 三生石上(FineUI控件)
S
SegmentFault 最新的问题

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
step by step crud operation in motoko - how to store and ...
Abdulsalam A · 2026-05-09 · via DEV Community
Cover image for step by step crud operation in motoko - how to store and retrieve data

Abdulsalam Abdulrahman (Amtech Digital)

To store 1 question and 4 options in Motoko efficiently, you should define a structured Record type to hold the data, rather than a raw Buffer. If you need to store multiple of these questions in a resizable container, you would use a Buffer to hold those records.

Here is the recommended implementation using an Actor to manage the question storage.

  1. Define the TypesUse a stable Record type to ensure the data persists across upgrades.
motoko

type Option = Text;
type Question = {
    questionText : Text;
    options : [Option]; // Array of 4 options
    correctOptionIndex : Nat; // Index 0-3
};

Enter fullscreen mode Exit fullscreen mode

  1. Implementation Using BufferThis actor initializes with a Buffer to store multiple Question records.
motoko

import Buffer "mo:base/Buffer";
import Array "mo:base/Array";

actor QuestionManager {

    // Define the type for the question
    public type Question = {
        questionText : Text;
        options : [Text]; // Expected size 4
        correctOptionIndex : Nat; // 0, 1, 2, or 3
    };

    // Buffer is a resizable array
    let questionsBuffer = Buffer.Buffer<Question>(10);

    // Function to add a question
    public func addQuestion(q : Question) : async () {
        // Simple validation: Ensure 4 options
        if (q.options.size() == 4) {
            questionsBuffer.add(q);
        };
    };

    // Function to get all questions
    public query func getQuestions() : async [Question] {
        // Convert buffer to immutable array for returning
        return questionsBuffer.toArray();
    };

    // Function to get total question count
    public query func getCount() : async Nat {
        return questionsBuffer.size(); //
    };
}

Enter fullscreen mode Exit fullscreen mode

Key Motoko Concepts

  • Used[Records]: { questionText : Text; ... } defines a structured object.

  • [Buffer]: Buffer.Buffer(10) creates a mutable, resizable container, ideal for managing lists of data on the heap.

  • [Array]: [Text] is a fixed-size array, perfect for the 4 options, ensuring they are immutable and easily shared.

  • ToArray: questionsBuffer.toArray() converts the mutable buffer into a shared, immutable array format required for canister return values.

Read more...
Motoko Book
Mops Docs