2. Hello World

The most basic basic program

What it looks like

Your file should be titled main.rs (automatically the name of your initial file within repl.it) and look something like this:

main.rs
fn main() {
  println!("Hello, world!");
}

If you are using repl.it, just click run. You will get an output that looks like this:

If you are running rust locally, then you need to run these commands:

$ rustc main.rs
$ ./main
Hello, world!

The rest of this book will only be referencing repl.it. If you want to keep going locally, check out the Rust Book.

Let's dig into this a bit more...

The first bit is this function definition. The same program in Java would look like this:

HelloWorldApp.java
class HelloWorldApp {
  public static void main(String[] args) {
    System.out.println("Hello World!"); // Display the string.
  }
}

Rust doesn't need quite that much. Rust isn't strictly object-oriented (or strictly functional). In Rust, the basic layout of a function is: fn plus_one(x: i32) -> i32 { x + 1 }

fn function_name(parameter: param_type) -> return_type {
  action_on parameter
}

We'll dig more into this later. Back to Hello World!

The main function is what is first run in every Rust program. Let's take a look at what it looks like if you don't have a main function:

This is the first example of one of Rust's many excellent error messages. main function not found makes it pretty clear that what we are missing is indeed the main function.

In the body of the function, we have println! (looks pretty familiar, right?). The big difference is that, while in Java System.out.println is a function, println! in Rust is a macro. println by itself is a function, but it's a macro if you add the ! at the end. We're gonna glaze over macros for now, but, if you are interested, check out this section of the Rust Book.

Last updated