DEV Community

Valentyn Kit
Valentyn Kit

Posted on

Rebuilding my C Redis clone in Rust taught me more Rust than any tutorial

I built a small Redis clone in C: a RESP parser, a command table, an append-only file for persistence. Recently I started building the same thing again in Rust, and rebuilding a project I had already finished has taught me more Rust than any from-scratch tutorial.

The reason is simple. The second time, the design is already solved. I know what the AOF has to guarantee, what the command table dispatches, what the parser must reject. So none of my attention goes to what to build. All of it goes to how Rust wants it built.

That turns the domain into a constant and the language into the only variable. Every difference I hit is pure signal about Rust, not noise about key-value stores.

The first difference shows up before any logic runs. In C, I built the substrate first: my own dynamic strings, my own hashmap, my own linked list. Hundreds of lines before a single command worked. In Rust, Vec, String, and HashMap are just there, so that whole layer disappears and I start at the actual command logic. A standard library quietly decides where your project even begins.

The sharper difference is in dispatch. In C it is a switch with argument counts I check by hand:

if (argc != 3) return err("wrong arg count");
switch (cmd) {
    case CMD_SET: return do_set(argv[1], argv[2]);
    case CMD_GET: return do_get(argv[1]);
    /* forget a case and it is a runtime bug */
}
Enter fullscreen mode Exit fullscreen mode

In Rust the same dispatch is an enum and a match, and the compiler will not build until every case is handled:

match cmd {
    Command::Set { key, val } => self.set(key, val),
    Command::Get { key }      => self.get(key),
}
Enter fullscreen mode Exit fullscreen mode

Same dispatch. One version cannot ship the missing-case bug I actually shipped in C.

If you already know a project cold, rebuild it in the language you are learning. You stop thinking about the problem and start feeling the language.

Top comments (0)