English 中文(简体)
Rust - HelloWorld Example
  • 时间:2024-11-03

Rust - HelloWorld Example


Previous Page Next Page  

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:UsersAdmin>mkdir HelloWorld-App
C:UsersAdmin>cd HelloWorld-App
C:UsersAdminHelloWorld-App>

    To create a Rust file, execute the following command −

C:UsersAdminHelloWorld-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:UsersAdminHelloWorld-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:UsersAdminHelloWorld-App>dir
//psts 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 pke 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 unpke functions. Macros are an extended version of functions.

Using the println! Macro - Syntax

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

Comments in Rust

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

Rust supports the following types of comments −

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

    Multi-pne comments (/* */) − These comments may span multiple pnes.

Example

//this is single pne comment

/* This is a
   Multi-pne comment
*/

Execute onpne

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

Execute onpne

Advertisements