Rust - HelloWorld Example



This chapter explains the basic syntax of Rust language through a HelloWorld example.

  • Create a HelloWorld-App folder and navigate to that folder on terminal

C:\Users\Admin>mkdir HelloWorld-App
C:\Users\Admin>cd HelloWorld-App
C:\Users\Admin\HelloWorld-App>
  • To create a Rust file, execute the following command −

C:\Users\Admin\HelloWorld-App>notepad Hello.rs

Rust program files have an extension .rs. The above command creates an empty file Hello.rs and opens it in NOTEpad. Add the code given below to this file −

fn
main(){
   println!("Rust says Hello to TutorialsPoint !!");
}

The above program defines a function main fn main(). The fn keyword is used to define a function. The main() is a predefined function that acts as an entry point to the program. println! is a predefined macro in Rust. It is used to print a string (here Hello) to the console. Macro calls are always marked with an exclamation mark – !.

  • Compile the Hello.rs file using rustc.

C:\Users\Admin\HelloWorld-App>rustc Hello.rs

Upon successful compilation of the program, an executable file (file_name.exe) is generated. To verify if the .exe file is generated, execute the following command.

C:\Users\Admin\HelloWorld-App>dir
//lists the files in folder
Hello.exe
Hello.pdb
Hello.rs
  • Execute the Hello.exe file and verify the output.

What is a macro?

Rust provides a powerful macro system that allows meta-programming. As you have seen in the previous example, macros look like functions, except that their name ends with a bang(!), but instead of generating a function call, macros are expanded into source code that gets compiled with the rest of the program. Therefore, they provide more runtime features to a program unlike functions. Macros are an extended version of functions.

Using the println! Macro - Syntax

println!(); // prints just a newline
println!("hello ");//prints hello
println!("format {} arguments", "some"); //prints format some arguments

Comments in Rust

Comments are a way to improve the readability of a program. Comments can be used to include additional information about a program like author of the code, hints about a function/ construct, etc. The compiler ignores comments.

Rust supports the following types of comments −

  • Single-line comments ( // ) − Any text between a // and the end of a line is treated as a comment

  • Multi-line comments (/* */) − These comments may span multiple lines.

Example

//this is single line comment

/* This is a
   Multi-line comment
*/

Execute online

Rust programs can be executed online through Tutorialspoint Coding Ground. Write the HelloWorld program in the Editor tab and click Execute to view result.

Execute online

Advertisements