In this example, you will learn how to print “Hello, World!” on the screen by using Rust language. We will run to code Rust Hello world program compile and run.
To understand this example, you should have knowledge of the following Rust language topics:
- Rust Input-Output (I/O)
Program to Display “Hello, World!”
Please create a file with the name of your choice and the extension should be .rs. In this file, you can write the code which you want to execute. The sample code is as below:
If you have not done the setup of the development environment yet, you can learn it here. The alternative is also available to use any online rust compiler.
fn main() {
println!("Hello, world!");
}
To compile your program, you can use the command:
#compile above program
rustc filename.rs
After you compile, you should be able to get the executables with the same name as your file name i.e filename.exe. Once you run your executable then you should be able to see the output of your program.
Output:
$rustc -o main *.rs
$main
Hello, world!
How “Hello, World!” program works?
“Hello, World” is probably the first program when you try to learn any language. In our series of Rust programs, we are also going to use the same program as our first example. so let us understand these 3 lines of code and learn how it works?
fn main() : First of all, we have fn main(). This is the main entry point of a Rust program. This is very similar to languages like C and C++, where the main() function is the entry point.
println!() :Then next we have is the println!() function which is taking our string as input. We can pass a string in double quotes to this function and it will print this for us on the output console. What we understood so far is that to print a simple text on console, we can make use of println!() function of Rust language.
Some more examples are:
fn main() {
println!("Hello, Rust!");
println!("We are going to Learn Rust Language");
}