“Hello, World”
Listing 2.1 shows the “Hello, World” application. Without a transfer control statement, it runs sequentially, displays the text “Hello, world!”, and then exits.
Code Listing 2.1. The “Hello, World” program
fn main() { println!( "Hello, world!"); }
Let’s examine the program.
First of all, the source code for the executable crate is saved in a file with an .rs extension, such as hello.rs. This is the standard extension for Rust source files.
Functions in Rust are preceded with the fn keyword. The function name, parameters, and return value follow, if any. Here is the syntax of a function:
fn func_name(parameters)->returnval
Snake case is the naming convention for functions in Rust. For this convention, each word of the function name starts with a lowercase letter and individual words are separated with underscores.
The main function is the entry point function for a Rust executable crate and the starting point of the application. In Rust, our main function has no function parameters or explicit return value.
Code for a function is encapsulated within curly braces, {}, which demarcates a function block. For the main function, the program concludes at the end of the main function block. It is the primary thread for the application.
In the main function, the println! macro displays the “Hello, world!” message and a linefeed. Function blocks can contain expressions, statements, and the macro. Macros in Rust have an exclamation point (!) after the name. In most instances, expressions and statements are terminated with semicolons.