Skip to main content

Actor messages

Send this actor a number and it replies with double the value. Run the example, then change the message or the handler.

Try a change

Change 21 to 8 and run again. Then change n * 2 to n * 3. Predict the reply before you run it.

actors.hew

actor Doubler {
    receive fn process(n: i64) -> i64 {
        n * 2
    }
}
 
fn main() {
    let doubler = spawn Doubler;
    match doubler.process(21) {
        .Ok(answer) => println(f"The reply is {answer}"),
        .Err(_) => println("The actor could not reply."),
    }
}
Continue in playground (new tab) ↗ Your edits open in a new tab.

Press Escape to leave the editor. runs your code.

Output

Run the example to see its output.

Expected from the original example

The reply is 42

Follow the message

spawn Doubler starts an actor. process(21) sends it a message and waits for its handler to finish. The handler returns the doubled number.

The call returns a Result. The match handles both outcomes: .Ok(answer) prints the reply, while .Err(_) reports that the actor could not reply. The underscore ignores the error’s details.

Handle an actor that has stopped

The first program takes the success branch. This one stops the same actor before sending the message, so you can see the error branch run.

stop(doubler) requests shutdown, and stopped(doubler) waits for it to finish. The failed call returns an error; the caller handles it and exits normally.

Try a change

Remove stop(doubler); and stopped(doubler);, then run again. Which branch runs now?

actors.hew

actor Doubler {
    receive fn process(n: i64) -> i64 {
        n * 2
    }
}
 
fn main() {
    let doubler = spawn Doubler;
    stop(doubler);
    stopped(doubler);
 
    match doubler.process(21) {
        .Ok(answer) => println(f"The reply is {answer}"),
        .Err(_) => println("The actor could not reply."),
    }
}
Continue in playground (new tab) ↗ Your edits open in a new tab.

Press Escape to leave the editor. runs your code.

Output

Run the example to see its output.

Expected from the original example

The actor could not reply.

Run it on your machine

Install Hew, then download an example and run it from the folder where you saved it.

macOS / Linux

hew build actors.hew -o actors && ./actors

Windows PowerShell

hew build actors.hew -o actors.exe
.\actors.exe