Rust: Hello world

I am starting to learn Rust and I am finding it very very interesting.

Rust is a statically typed, native programming language that pretends to be a nice and modern replacement for C and C++. It implements a very nice set of rules that make your program robust and reliable on memory handling in compile time.

Nice working examples of Rust are the Firefox browser since version 57 (a lot of modules were written in it) [https://blog.mozilla.org/blog/2017/11/14/introducing-firefox-quantum/] and Redox, a UNIX-like operating system written in Rust from the scratch [https://www.redox-os.org/]

So, this is a “Hello world” written in Rust:

// This is my first program in Rust

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

To compile this, we need to compile it with the Rust compiler. Something like this in a Linux environment:

rustc hw.rs -o hw

All the Rust programs must have a .rs extension.

“main” is the name of the function that will be the entry point to our program. So, when the program is invoked, the OS will call the main function.

The “fn” reserved word means “main()” is a function that is being declared inside the curly braces. Since there is nothing more expressed in the declaration, the compiler understands the function does not return anything (similar to a “void” function in C).

println! is a macro (the exclamation mark indicates that) that receives a “str” literal (a Rust low level string, something similar to a const char* in C) and a set of parameters that can be passed as additional arguments to this macro. This macro prints a full line of text in the standard output.

The curly braces work in the same way they do in C or C++. The semicolon usage is similar, though in Rust you do not need to write it if you are returning an expression instead of executing an instruction (more on this later).

So, happy Rusting! :)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s