Getting Familiar with Rust
Get introduced to Rust and its features.
We'll cover the following
Introduction
Rust is a low-level programming language that was developed to achieve safety in a field where it’s easy to make mistakes.
At high-level programming, we might ask ourselves, “Is Rust helpful to us?”
One of the biggest advantages of using Rust is that it solves the issues we face in scalability. Another benefit is that we can use a low-memory footprint language for our projects.
Rust might seem unusual compared to other languages, such as Python or Ruby. However, once we’re done with this course, it’ll start to feel intuitive.
Let’s take a look at the first code example.
Hello World
We’ll write a Hello World program. Most of the time, they are simple programs that print the text “Hello World!”
fn main() {println!("Hello World!");}
If we click “Run”, we’ll see the result in the standard output.
We use fn
to declare a function and the macro println!
to print the text ‘Hello World!’ to the output.
Try changing the content of the macro to see how programming in Rust feels.
Object-oriented programming
Rust is a general-purpose language and not an object-oriented language. However, we can apply some of the concepts from the object-oriented programming (OOP) paradigm.
The following code will give an error upon running it. It is left as an exercise for you to figure out the bug present in the code and try to solve it.
#[derive(Debug)]struct Animal {legs: i32,sound: String,size: f32}impl Animal {fn new(legs: i32, sound: String, size: f32) -> Self {Animal { legs, sound, size }}}fn main() {println!("{:#?}", Animal::new("woof".to_string(), 0.32));}
If you are finding it difficult to figure out the bug, click the “Show Hint” button.
If you’re stuck, click the “Show Solution” button to see how you can solve the above bug.
We’ll cover the struct
concept in a later lesson. For now, let’s consider a struct
as similar to a class
in OOP. In the above example, Animal
is a struct
that needs to be instantiated in a new object.
If we click “Run,” it’ll return an error.
We can become better programmers by using Rust to create more stable software.