Let’s Rust (1nd part): Writing the first function in Rust.

in-n-out.cloud
LetsRust
Published in
2 min readDec 17, 2022

Hey There Everyone,

I’ve decided to start learning Rust and will share my journey here. Thank you for following along. If you are starting programming in Rust, let’s connect, use #letsrust on Twitter, and good luck.

So part 1, let’s begin:

Of curse, it will be a “Hello world” print function. A typical application will print out a “Stand with Ukraine!” statement.

My Rust version:

rustc - version
rustc 1.66.0 (69f9c33d7 2022–12–12)

Create a source p1.rs file:

touch p1.rs

Write the first function called main():

fn main() {
println!("Stand with Ukraine!");
}

The main function is always the first code that runs in every executable Rust program.

The function body is wrapped in {}. Rust requires curly brackets around all function bodies.

The println! is called a macro in Rust. Fundamentally, macros are a way of writing code that writes other code, which is known as metaprogramming. Macros are executed at compile time. The difference in defining function and macro in Rust is the usage of! character.

In Rust, the line ends with a semicolon (;), which indicates that this expression is over.

Run formatter and linter:

rustfmt p1.rs

Compile and execute like so:

rustc p1.rs

Verify the compiled file was created:

=>ll
total 944
drwxr-xr-x 4 devnull staff 128B Dec 16 23:23 .
drwxr-xr-x 4 devnull staff 128B Dec 16 23:08 ..
-rwxr-xr-x 1 devnull staff 466K Dec 16 23:23 p1
-rw-r - r - 1 devnull staff 49B Dec 16 23:23 p1.rs

Simply run compiled program:

=>./p1 
Stand with Ukraine!

My useful notes:

  • Note 1: for filenames with more than one word, use underscore.
  • Note 2: Rust style is to indent with four spaces, not a tab.
  • Note 3: Place the opening curly bracket on the same line as the function declaration, adding one space between.
  • Note 4: you must define macros or bring them into scope before you call them in a file, as opposed to functions you can define and call anywhere.

For now, I’m coding in IntelliJ, and I like it.

Happy coding and #letsrust more!

--

--

in-n-out.cloud
LetsRust

Staff Cloud Engineer working on k8s, cloud, microservices. Millennial. Coffeholik. Started #LetsRust on medium