Obsidian/Zettelkasten/Permanent Notes/Programming/Rust/Chapter 1 - Introduction.md

1.8 KiB

First things first

Chapter 1 takes you through an introduction to rustc -- an older version of compiling and running rust that predates Cargo. The first thing I did was create a 'Hello, world!' program.

I also learned that when naming files, the convention is underscores:

Good: hello_world.rs

Bad: helloworld.rs

What does a Rust program look like?

Here was our full hello world program:

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

First, there's the fn main() function. This is always the first piece of code that will run in a Rust program.

Second, indents always happen with 4 spaces, not a tab.

Third, the print statement is doing something a little different. It is a macro, not a function. Macros use ! at the end, while functions do not.

Fourth, each line ends with a semicolon. Much like C.

Cargo!

Cargo is Rust's dependency manager and project creator. Using "cargo new xxx" will create a new project in a folder xxx.

Cargo build will compile and build things. Cargo run will do build and then run the program!

Cargo check will compile everything and check for errors, but won't build an executable yet.

Cargo uses a .toml to manage everything. This is what one of those looks like:

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

[dependencies]

This file makes sures that when building all the right dependencies and their versions are in your files. This is great for management of dependencies, and will also help when writing code.

Release vs. Debug

When ready to build something for release, use "cargo build --release". This tells the compiler to include optimizations when building the code. This lengthens compile time, but will make the target code faster. Code is then stored in target/release insetead of target/debug.