This is my first program in Rust, obviously, a “Hello World“! :)
Two ways of creating it:
1. Everything manually
a. Need to create a file with .rs extension. In my case: HelloWorld.rs
b. Write the actual program in that file:
// Hello World in Rust
/*
* Same multiline comment like in C
*/
fn main()
{
println!("Hello world");
}
c. Go to the command line and compile the file with the rustc compiler
rustc HelloWorld.rs -o HelloWorld
d. Execute the binary file
./HelloWorld
Hello world
2. Using cargo.
a. cargo is the Rust package manager that helps you managing dependencies and also is useful in the build process. You can use it to create your program and compile it. So, we can create a new “cargo package“:
cargo new HelloWorld
b. That creates a new “cargo package” called “HelloWorld“: cargo new creates a new “HelloWorld” directory, that contains a Cargo.toml descriptor file and a src directory that contains a main.rs skeleton file that already contains a “Hello World” project similar to the one I wrote above:
fn main() {
println!("Hello, world!");
}
c. To compile the package, we can build it using cargo too:
cd HelloWorld
cargo build
d. If everything is ok, a new directory called target is created and inside it, directories for debug or release builds (cargo build --release). Going to the debug folder we can run the HelloWorld executable.
3. “Hello World” content
The comments are similar to the C-like languages: // for simple line and /* */ for multiline comments.
The “fn” keyword identifies a block as a Rust function. All functions in Rust have a name and a set of arguments. The return type will be deduced automatically by the compiler.
“main“, as in C, is the program entry point and is the function that is executed when you invoke the program from the command line.
“println!” is a Rust macro that prints a line of the text specified. A Rust macro is a piece of code able to generate code by itself (metaprogramming).
This is it for now. I will continue writing about Rust while learning it. Thanks for reading!
4. Comparison with C++
This is the most similar implementation of “Hello world” in C++:
#include "fmt/core.h"
int main()
{
fmt::print("Hello world\n");
}
I used libfmt to print the "Hello world” text to make both implementations as similar as possible.
Notice that Rust does not need any #include stuff. Actually Rust lets you import libraries in a modern way (similar to Java imports or C++20 modules) but println! is a macro included in the standard library, imported by default.
Function main() is also the program entry point in Rust, but it does not return anything, in C++, it MUST return an int, that, if not explicitly mentioned, it will return 0.