Hello World in Rust

Published on 05 December 2018 (Updated: 05 December 2018)

Hello World in Rust

In this article, we’ll demonstrate how to implement Hello World in Rust.

How to Implement the Solution

Hello World in Rust is very similar to Hello World in C:

fn main() {
    println!("Hello, World!");
}

In fact, Rust’s implementation is even easier. There’s no need to import any IO packages to get access to println. We just need to create our main function, add our print code, and we’re done.

But, wait a minute. That print line seems a little off. What’s with the bang !? To be honest, I had to do a bit of digging for this. As it turns out, println is not a function at all. It’s a built-in macro. That’s a new term for me, so let’s learn a little more about it.

According to the Rust Programming Language book, macros are a language feature that allow you to abstract syntax. In other words, macros allow you to do some metaprogramming by adding grammar to Rust’s abstract syntax tree. Perhaps an example would make more sense:

macro_rules! println {
    () => (print!("\n"));
    ($fmt:expr) => (print!(concat!($fmt, "\n")));
    ($fmt:expr, $($arg:tt)*) => (print!(concat!($fmt, "\n"), $($arg)*));
}

This is the actual definition of the println macro in Rust. I won’t go into exactly what’s happening, but basically we have defined three available patterns for println: empty, one argument, and variable arguments. Rust functions don’t have support for variable arguments, so you can add the functionality with macros.

That said, I’m only just learning macros for the first time, so I recommend an article by Kasper Anderson called why Rust has macros. It’s quite thorough, and I think it does a better job than Rust’s documentation.

How to Run the Solution

As always, we can try out this code using an online Rust compiler. All we need to do is drop the code into the editor and hit run.

Alternatively, we can download the latest Rust compiler and a copy of the solution. Then, assuming the compiler is in the path, navigate to folder with the solution and run the following in Windows:

rustc hello-world.rs
hello-world.exe

Of course, in Unix-based environments, the following will run the new binary:

./hello-world

And, that’s it! “Hello, World!” should print directly to the console.1


References

  1. J. Grifski, “Hello World in Rust,” The Renegade Coder, 28-March-2018. [Online]. Available: https://therenegadecoder.com/code/hello-world-in-rust/. [Accessed: 05-Dec-2018].