Let's get started by showing a welcome message to the players of our game. Open your favorite text editor (like Notepad++ or gedit) for a new file and type in the following code:
// code in Chapter1\code\welcome.rs fn main() { println!("Welcome to the Game!"); }
The steps to be performed are as follows:
- Save the file as welcome.rs. The .rs extension is the standard extension of Rust code files. Source file names may not contain spaces; if they contain more than one word, you can use an underscore, _, as a separator, for example: start_game.rs.
- Then compile it to native code on the command line with rustc.welcome.rs. This produces an executable program, welcome.exe, on Windows or welcome on Linux.
- Run this program with welcome or./welcome to get the output:
Welcome to the Game!
The output executable gets its name from the source file. If you want to give the executable another name, like start, compile it with the option -o output_name, as shown below:
rustc welcome.rs -o start
The rustc -O produces native code optimized for execution speed (equivalent to rustc -C opt-level=2); the most optimized code is generated for rustc -C opt-level=3.
Compiling and running are separate consecutive steps, contrary to dynamic languages like Ruby or Python where these are performed in one step.
Let's explain the code a bit. If you have already worked in a C, or Java, or C# like environment, this code will seem quite familiar. As in most languages, execution of code starts in a main() function, which is mandatory in an executable program.
In a larger project with many source files, the file containing the main() function would be called main.rs by convention.
We see that main() is a function declaration because it is preceded by the keyword fn, short and elegant like most Rust keywords. The () after main denotes the parameter list, which is empty here. The function's code is placed in a code block, surrounded by curly braces { }, where the opening brace is put by convention on the same line as the function declaration, but separated by one space. The closing brace appears after the code, in the column right beneath fn.
Our program has only one line, which is indented by four spaces to improve readability (Rust is not whitespace sensitive). This line prints the string Welcome to the Game!. Rust recognizes this as a string, because it is surrounded by double quotes " ". This string was given as argument to the println! macro (the ! indicates it is a macro and not a function). The code line ends in a semicolon, ;, as most, but not all, code lines in Rust do (see Chapter 2, Using Variables and Types).
Write, compile, and execute a Rust program, name.rs, that prints out your name.
What is the smallest possible program in Rust in terms of code size?
The println! macro has some nice formatting capabilities and at the same time checks when compiling whether the type of variables is correct for the applied formatting (see Chapter 2, Using Variables and Types).