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.
- 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
};
- 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(); //
};
}
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
United States
NORTH AMERICA
Related News
Amazon Employees Are 'Tokenmaxxing' Due To Pressure To Use AI Tools
20h ago
UCP Variant Data: The #1 Reason Agent Checkouts Fail
6h ago

Décryptage technique : Comment builder un téléchargeur de vidéos Reddit performant (DASH, HLS & WebAssembly)
16h ago
How Braze’s CTO is rethinking engineering for the agentic area
10h ago
Encryption Protocols for Secure AI Systems: A Practical Guide
20h ago