Rust - Part 1

Written on
This article is for those who already have some experience with rust, and want to refresh the concepts.
All the articles from this series are condensed versions of Rust official book, this post covers Chapter 1 from the book.

 

Chapter 1

1. Getting started

To install rust

$ curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf | sh 

If you are paranoid about executing a random sh file on your pc, you can visit the website, download the shell file and try to make sense out of it. If you are running another OS, refer this

rustup update

rustup self uninstall

rustc --version

2. Hello World

mkdir hello_world

cd hello_world

Create a file called main.rs with the following content

fn main() {
    println!("Hello, world!");
}

Save the file and now you can compile the file by running

rustc main.rs

Now you should be able to see an executable file called main.  Unlike Java this doesn't produce a bytecode, it directly gives you a system executable file

Run the program by executing the file ./main and you should be able to see the Hello World.

3. Hello Cargo

Cargo is a package manager and it also has some utility to help speed up the process.

Cargo should already be installed when we install rust, we can verify that by running

cargo --version

Let's try to create a project using cargo

cargo new hello_cargo

cd hello_cargo

Note: git will be auto initialized when we create a project using cargo.

If we take a look at the files generated, we should have two files - Cargo.toml and src/main.rs

Cargo.toml  contents might look like this 

[package]
name = "hello_cargo"
version = "0.1.0"
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]

 I hope everything is self explanatory here.

cargo build - To build the project - Our executable will be inside <project>/target/debug

cargo run - To compile and build the program

cargo check - Check if there are any errors

cargo build --release - To build the project with optimizations

 

End of Chapter 1

 




Tags · Rust, Tech, Blog