← Table of contents

1.1 Giving Shape to Nothing

Before casting a part, the craftsman cuts the mould. Not because that is how it is done - because without the mould, the material does not know what to become. The workshop already has order: tools, checks, a gate at the entrance. The artifact carries the name of a task manager and has no idea what a task is.

What You Need

A task is not just a line of text. It has several parts: a sequence number, a title, and a status - whether it is done or not. Before anything can be done with a task - passing it around, printing it, marking it complete - the compiler must know how it is structured. Right now it does not. In the code, a task does not exist.

The Mould

In Rust, the shape for related data is described with the keyword struct. Here is a task:

struct Task {
    id: u64,
    title: String,
    status: bool,
}

Task is the name of the shape. Inside are three fields: id of type u64, title of type String, status of type bool. What those types mean will be covered in the next chapter; for now, take them as given.

Add this to main.rs and create the first task:

struct Task {
    id: u64,
    title: String,
    status: bool,
}

fn main() {
    let task = Task {
        id: 1,
        title: String::from("Buy coffee"),
        status: false,
    };

    println!("Task #{}: {}", task.id, task.title);
    println!("Done: {}", task.status);
}

A struct is initialised inside curly braces: field name, colon, value. String::from creates a string from a text literal - why not just "Buy coffee" is explained in chapter 1.2. Fields are accessed with a dot: task.id, task.title, task.status.

make run
Task #1: Buy coffee
Done: false

make ci passes.

The Result

The artifact knows what a task is: there is a shape, there are fields, the compiler works with it. The task has no methods yet, no list, no operations. The mould exists - and from it, building can continue.

The complete tq code for this chapter is in 1-a-task/01-giving-shape-to-nothing/.


Lore: String::from and String Literals

"Buy coffee" is a string literal, of type &str. It is a reference to text stored directly in the compiled binary. It cannot be modified - only read.

String is a different thing: a string the program creates at runtime. It can be modified; &str cannot. String::from("Buy coffee") creates such a string from a literal.