24 days of Rust - uuid

Important note: this article is outdated! Go to http://zsiciarz.github.io/24daysofrust/ for a recent version of all of 24 days of Rust articles. The blogpost here is kept as it is for historical reasons.

Writing the Postgres article reminded me of one more cool thing in PostgreSQL - native support for the UUID type. The popular web framework Django will soon get a UUID field, Rails already support it. So what's the big deal?

Simply put, using UUIDs can improve distributed systems by removing the need for a centralized ID generation. Let me quote Andrzej Krzywda's justification:

For years, I have been thinking that centralised id generation is the natural way. Seems obvious. After I learnt mote about UUID, I start seeing more and more good things about it. It allows for less coupling between components/services. You no longer need to 'ask' for the id. In case of JavaScript frontends it solves the problem of whether to block the UI, when we create a new resource.

For me, looking from the web development perspective, this is an area of experimentation as I'm not using UUIDs in any of my public projects (yet). However most of the languages I use have a function or library to generate UUIDs and Rust is no exception here. The uuid crate was once in the standard library, but got pulled out during the cleanup.

As usual we'll start by adding the dependency to Cargo.toml:

uuid = "~0.1.1"

Let's generate a few UUIDs and display them in the most familar form:

extern crate uuid;

use uuid::Uuid;

fn main() {
    for _ in range(0, 10u) {
        println!("{}", Uuid::new_v4().to_hyphenated_string());

The example output would look like:

$ cargo run

We can use the parse_str() method to check if a string represents a valid UUID and convert it to an Uuid value.

println!("{}", Uuid::parse_str("d27cdb6e-ae6d-11cf-96b8-44455354000"));
println!("{}", Uuid::parse_str("x27cdb6e-ae6d-11cf-96b8-444553540000"));
println!("{}", Uuid::parse_str("d27cdb6-eae6d-11cf-96b8-444553540000"));
println!("{}", Uuid::parse_str("d27cdb6e-ae6d-11cf-96b8-444553540000"));

(Web developers might recognize that specific value.) Here's the output:

$ cargo run
Err(Invalid length; expecting 32, 36 or 45 chars, found 35)
Err(Invalid character; found `x` (0x78) at offset 0)
Err(Malformed; length of group 0 was 7, expecting 8)

The code for this and previous days is in the 24daysofrust repository on GitHub.

See also

Code examples in this article were built with rustc 0.13.0-nightly and uuid 0.1.1.

Photo by Jonathan Cohen and shared under the Creative Commons Attribution-NonCommercial 2.0 Generic License. See https://www.flickr.com/photos/jonathancohen/15069301735