In this article, we will explore the first rust program. Here is the rust program to print “Hello World”. The program looks very similar to a C “hello world” program.


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

To run this program, we need to install rust compiler(rustc); Actually we will install the compiler and rust package manager(cargo) through the rust toolchain manager(rustup). Follow the instructions at https://rustup.rs/ .

If you are using Linux or MacOS then it just simple command curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

Once the installation is complete, create a new folder for this project. I named the folder as “hello_world” – you can use any name. Run cargo init command inside the folder. It would create two files – cargo.toml and src/main.rs. We will learn about cargo.toml in another article.

Type/copy the above code using your favorite editor into src/main.rs and then run the following command cargo run it will build and run your program.

$ cargo run
   Compiling hello_world v0.1.0 (/home/samuel/rust/hello_world)
    Finished dev [unoptimized + debuginfo] target(s) in 0.63s
     Running `target/debug/hello_world`
Hello, world!

That’s it! You created your first rust program, compiled it and ran it.

The rust compiler is a very powerful in detecting bugs in the program and timesaver because it provides useful hints to fix the reported problems. However, I do not directly invoke the compiler rustc instead I use the package manager cargo to invoke rustc. If you are from C background, `cargo` eliminates the need for build system(such as Make/CMake). We will explore the benefits on using cargo in another article.

Lets compare the program to the following C program.


void main() {
    printf("Hello World\n");
}

The main difference between these hello world programs is to define a function in rust we need to use fn keyword. C requires explicit void datatype to be specified to indicate that the function does not return a value whereas rust does not require that. To print a string, C program uses `printf` function where as in rust program, I used a `println!` macro; yes it is macro and not a function.

This article is to get started on rust programming by installing the required tools. One of the important tool during development is the editor – I would recommended using vscode or clion for writing rust programs because of the integration with rust analyzer which makes easier to write rust programs.

This article can be viewed as video here

In the next article I will cover primitive data types and how to write basic functions.

Categorized in:

Tagged in:

,