0% found this document useful (0 votes)
10 views79 pages

Rust+Programming+for+Beginners+Simplified+Version True

The document is a beginner's guide to Rust programming, covering essential topics such as installation, compilation, data types, and the use of Cargo as a package manager. It explains key concepts like variables, mutability, control flow, and functions, providing examples and commands for practical application. The content is structured with an index and includes sections on various data types, including scalars and compounds, as well as numeric operations.

Uploaded by

rod
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views79 pages

Rust+Programming+for+Beginners+Simplified+Version True

The document is a beginner's guide to Rust programming, covering essential topics such as installation, compilation, data types, and the use of Cargo as a package manager. It explains key concepts like variables, mutability, control flow, and functions, providing examples and commands for practical application. The content is structured with an index and includes sections on various data types, including scalars and compounds, as well as numeric operations.

Uploaded by

rod
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 79

For my son

Ascendance.dev ©
“Special Forces for Science and Knowledge”

-Arthur L.
Rust Programming for Beginners Simpli-
fied Version ©
Index

14 Rust Compilation
16 Rust Installation
20 Cargo
22 Data Types
26 Scalar Types
27 Bit Concept
28 Integer Types
30 Large Integers
32 Floating-point numbers
34 Numeric Operations
36 Hexadecimals
38 Octal Numbers
40 Variables and Mutability
42 The ‘let’ keyword
44 The ‘const’ keyword

10 Ascendance.dev
Index

46 The ‘mut’ keyword


48 Shadowing
50 Booleans
52 Characters
54 TupleType
58 Arrays
60 Functions
62 Cargo
64 Comments
66 Control Flow
68 If-else if expressions
70 While loop
72 For loop

11
Symbols used in this book

12
Symbols used in this book

Mind Map

Concept

Theory

Code

Question

13
Rust Compilation

• Rust is a systems programming language that aims for safety, performance, and
concurrency. To make a simple Rust project, you have to write the Rust code,
compile it, and then run the compiled binary. We’ll use the basic “Hello, World”
program to walk through the compilation process.

1. Write or create a Rust source code file:


• First, create a new file called `main.rs` and write the code inside it.

2. Compile the Rust source code:


To compile the Rust code, open a terminal (command prompt) and navigate to the
directory where your `main.rs` file is located. Then, run the following command:
rustc main.rs
`rustc` is Rust’s compiler - it compiles your source code into machine code, which
can then be executed directly by your computer. The compiled binary will have the
same name as your source file, but without the `.rs` extension, so for our example,
it will result in a file named `main` (or `main.exe` on Windows).

Now that the code is compiled, you can execute the binary generated in the previ-
ous step. Run the following command:

On Linux and macOS:

```
./main
```

On Windows:

```
main.exe

14 Ascendance.dev
Rust Compilation

File name: main.rs

You should see the output "Hello, World!" printed in your terminal. Con-
gratulations! You have successfully written, compiled, and executed a
Rust program.

In summary, the compilation process in Rust involves creating a source


code file (e.g., `main.rs`), using the `rustc` command to compile it, and

15
Rust Installation

16 Ascendance.dev
Rust Installation

FOR INSTALLING RUST


Mac /Linux
Run the command on terminal:
$ curl --proto ‘=https’ --tlsv1.2 https://sh.rustup.rs -sSf | sh

Mac
Run the command on terminal (get a C compiler):
$ xcode-select --install

Windows
You’ll need Visual Studio 2022
• “Desktop Development with C++”
• The Windows 10 or 11 SDK
• The English language pack component

Troubleshoot
Get Rust installed version on terminal:
$ rustc --version

Update
$ rustup update

Uninstall
$ rustup self uninstall

17
Rust installation
• The rustup tool is used for installing and manag-
ing Rust.

Rustup is a tool that helps you to install and man-


age different versions of the Rust Programming
Language from official release channels. With
Rustup, it’s easy to switch between stable, beta,
and nightly compilers, and keep them up to date.
Cargo

Cargo is the default package manager and build tool for the
Rust programming language. It helps developers manage
their project’s dependencies, compile source code, run tests,
and distribute their compiled applications easily. Essentially,
Cargo streamlines the entire development process in Rust,
allowing programmers to focus more on coding.

20 Ascendance.dev
Cargo

Building Cargo consists of several commands, including:

1. `cargo build`: This command compiles your Rust project and


generates an executable binary in the “target/debug” directory.
It also downloads and compiles all dependencies specified in the
“Cargo.toml” file.

2. `cargo run`: This command not only builds the project but also
immediately runs the compiled binary. It is particularly useful
during development because it simplifies the process of testing
your code.

`cargo check` is another useful command that analyzes your


source code and determines if it has any syntax or type errors
without actually building it. This works much faster than the `car-
go build` command because it does not create an executable
binary, which can save developers a significant amount of time
during the development process.

Building for release is an essential step in the deployment of a


Rust application. To optimize your code for better performance,
use the command `cargo build --release`. This prepares your
project with optimizations, creating a more efficient binary in the
“target/release” directory that is ideal for distribution.

21
Data Types
Scalar Types:
• Integers (whole numbers)
• Floating-point numbers (decimals)
• Booleans (true/false)
• Characters (individual letters/symbols)

Primitive Compound Types


• Tuples
• Arrays
Data Types

24 Ascendance.dev
Data Types

Rust has several data types: scalars and compounds.


Scalar types include integers, floating-point numbers,
booleans, and characters. Compound types structure
multiple values: tuples group together values of differ-
ent types, and arrays hold multiple values of the same
type. Strings, a special type, store sequences of char-
acters. All these types help programmers model re-
al-world problems in their code.

25
Scalar Types

Scalar types in Rust consist of four main categories:


• integers (whole numbers)
• floating-point numbers (decimals)
• Booleans (true/false)
• Characters (individual letters/symbols). These basic
data types help you manipulate and represent values
and are essential for programming in Rust.

26 Ascendance.dev
Bit Concept

A bit is the fundamental unit of information in comput-


ing and digital communications representing a binary
state with two possible values typically “1” or “0”. It can
also symbolize true/false or on/off. A bit’s relation to
its physical state depends on the specific device or pro-
gram. Bits form larger units like bit strings bit vectors
or bit arrays. Eight bits create a byte though byte size
can vary. One bit is equivalent to the information entro-
py of an equally probable binary variable also called a
shannon. The symbol for a bit is either “bit” or lower-
case “b”.

27
Integer Types

Rust scalar types include integer types which repre-


sent numbers without fractional parts. Integers can
be signed (negative or positive) or unsigned (only pos-
itive). There are different sizes such as: 8-bit, 16-bit,
32-bit, 64-bit and 128-bit. For example i32 is a signed
32-bit integer while u64 is an unsigned 64-bit integer.
The isize and usize types depend on the computer’s ar-
chitecture (32 or 64 bits). Integer literals can be written
in: decimal, hex, octal, binary or byte forms.
If unsure about which integer type to use Rust’s default
i32 is a good starting point. Use isize or usize for index-
ing collections.

28 Ascendance.dev
Integer Types
File name: main.rs

$ cargo run

Output:

29
Large integers

How to work with Really Big Numbers for: Science, Re-


search, Space, Physics, Astronomy; using Rust?

30 Ascendance.dev
Large integers

In simple terms, Rust has some basic building blocks (called


primitives) which have a fixed size in terms of bits. A bit is a tiny
piece of computer memory that can store either 0 or 1. The
number of bits determine how many different values you can
store using that type of building block.

For example, Rust has a type called `i64`, which uses 64 bits,
and it can store positive and negative whole numbers. The larg-
est number it can store is 2^63-1, which is a huge number but
not as huge as 99e100 (which is a 1 followed by 100 zeroes).

Similarly, Rust has other types like `i128` for even larger whole
numbers, and `u128` for even larger non-negative whole num-
bers. However, none of these can store numbers as large as
99e100.

If you need to work with really big numbers, you’ll need to use
some special types that can grow as needed. These types are
not included by default in Rust and you’ll either need to cre-
ate them yourself, or use a package that someone else already
made, like the `num` crate.

31
Floating-point numbers

Floating-point numbers are values with decimal points,


and Rust supports two types: f32 (32 bits) and f64 (64
bits). By default, Rust uses f64, offering better precision
and similar speed to f32 on modern CPUs. Both types
are signed and abide by the IEEE-754 standard. For ex-
ample, declaring variables ‘x’ as f64 and ‘y’ as f32:

32 Ascendance.dev
Floating-point numbers
File name: main.rs

$ cargo run

33
Numeric Operations

Rust offers various numeric operations for number


types, including addition, subtraction, multiplication,
division, and remainder. Integer division truncates,
rounding down to the nearest integer.

34 Ascendance.dev
Numeric Operations
File name: main.rs

$ cargo run

35
Hexadecimals

A hexadecimal is a base-16 number system represent-


ing numbers using 16 symbols: 0-9 for values 0-9, and
A-F for values 10-15. It’s important because it simplifies
the representation and manipulation of binary data.
Each hex digit can represent 4 bits, making it easier to
read and write compared to binary.

For example, the binary string ‘1010’ can be represent-


ed as the hex digit ‘A.’ In Rust, you write hexadecimals
with the “0x” prefix.

This can be helpful when working with color codes,


memory addresses, or bitwise operations.

36 Ascendance.dev
Hexadecimals
File name: main.rs

$ cargo run

37
Octal numbers

An octal number system comprises numbers represent-


ed using 8 unique digits: 0 to 7. It’s essential for simpli-
fying binary numbers and useful in computer program-
ming for historical reasons. Octal numbers are written
with an ‘0o’ prefix, followed by base-8 digits.

Example: The octal value 0o572 corresponds to the


decimal value (5 x 8²) + (7 x 8¹) + (2 x 8⁰) = 378.

In Rust, we can convert octal to decimal with `i32::-


from_str_radix`, and format decimal back to octal using
`format!(“{:o}”, value)`.

38 Ascendance.dev
Octal numbers
File name: main.rs

$ cargo run

39
Variables and Mutability
The `let` keyword
The `const` keyword
The `mut` keyword
The `let
` let`` keyword

let: The `let` keyword is used for creating and initializ-


let:
ing a variable. By default, a variable declared with `let`
is immutable, meaning its value cannot be changed
after initialization. This enforces safety and security in
your code.

42 Ascendance.dev
The `let
` let`` keyword
File name: main.rs

$ cargo run

43
The `const
` const`` keyword

const: The `const` keyword is similar to `let`, but is used


to declare a constant variable. This means its value nev-
er changes and must be initialized with a constant ex-
pression (not a value computed at runtime). Constants
are always immutable and have a global scope.

44 Ascendance.dev
The `const
` const`` keyword
File name: main.rs

$ cargo run

45
The `mut
` mut`` keyword

mut: The `mut` keyword is used to make a variable mu-


table, allowing its value to change after initialization.
This is useful when working with data that needs to be
modified during program execution.

46 Ascendance.dev
The `mut
` mut`` keyword
File name: main.rs

$ cargo run

47
Shadowing

Shadowing is a concept in Rust programming where


you declare a new variable with the same name as an
existing variable, effectively “shadowing” the original
variable. This allows you to change the value and type
of a variable by shadowing it, without affecting the
original value. This can be useful in cases where you
need to perform transformations on a variable while
keeping the same name.

48 Ascendance.dev
Shadowing
File name: main.rs

$ cargo run

49
Booleans

Booleans (The Boolean Type)


Booleans, in the context of programming, are a data
type that can represent one of two possible values:
true or false. They are named after George Boole, a
mathematician who developed Boolean algebra, an
essential concept in computer science.

In Rust programming, Booleans are represented by


the `bool` data type. They are commonly used in con-
ditional statements, such as `if`, `else`, and `while`, to
control the flow of the program’s execution based on
specific conditions.

50 Ascendance.dev
Booleans
File name: main.rs

$ cargo run

51
Characters

Characters in Rust The Character Type


A “Character Type” in Rust refers to the data type that
represents an individual Unicode character. It is de-
noted by the keyword `char`, and it can store a single
Unicode character, taking up 4 bytes of memory. Uni-
code characters include not only standard ASCII char-
acters (like digits, English letters, and common sym-
bols) but also a wide
range of international characters, special symbols, and
emojis.
Accented letters in several languages; Japanese, Chi-
nese, and Korean; emojis, and zero-width spaces are
all valid char values in Rust

Here’s a code example to illustrate how to work with


the character type in Rust:

52 Ascendance.dev
Characters
File name: main.rs

$ cargo run

53
Tuple Type

Tuple type is a compound data structure in Rust that


allows you to bundle multiple heterogenous (values
with different types) together as a single entity, with
a fixed length. You can think of tuples as a simple way
to create a collection of differing types, while keeping
the data organized and easily accessible through in-
dexing.

54 Ascendance.dev
Tuple Type
File name: main.rs

$ cargo run

55
Tuple Type

56 Ascendance.dev
Tuple Type
File name: main.rs

$ cargo run

57
Arrays

An “Array Type” is a fixed-size, homogeneous data


structure in Rust programming language that can
store multiple values of the same data type. In sim-
pler terms, it’s a collection of elements where each
element is of the same type, and the number of ele-
ments is fixed, meaning the size of the array is con-
stant.

Here’s a code example to demonstrate the use of an


array type in Rust:

58 Ascendance.dev
Arrays
File name: main.rs

$ cargo run

59
Functions

Functions in Rust are reusable pieces of code that perform


“fn”” keyword, fol-
a specific task. They are defined with the “fn
lowed by the function’s name, a list of input parameters, and
the return type of the function if applicable. Functions allow
us to modularize, make our code more organized, and pre-
vent repetition by abstracting common functionality into one
place.

Arguments and parameters are essential parts of a function.


Parameters are the variables listed in the function definition,
while arguments are the values passed to a function when
it’s called. Simply put, parameters are the placeholders for
the data a function needs, and arguments hold the actual
data being supplied to the function.

In Rust, it is a convention to name functions using the lower


snake case. This means separating words with underscores
and using lowercase letters for the words (example: calcu-
late_sum).

60 Ascendance.dev
Functions
File name: main.rs

$ cargo run

61
Cargo

Cargo is the default package manager and build tool for the
Rust programming language. It helps developers manage
their project’s dependencies, compile source code, run tests,
and distribute their compiled applications easily. Essentially,
Cargo streamlines the entire development process in Rust,
allowing programmers to focus more on coding.

62 Ascendance.dev
Cargo

Building Cargo consists of several commands, including:

1. `cargo build`: This command compiles your Rust project and


generates an executable binary in the “target/debug” directory.
It also downloads and compiles all dependencies specified in the
“Cargo.toml” file.

2. `cargo run`: This command not only builds the project but also
immediately runs the compiled binary. It is particularly useful
during development because it simplifies the process of testing
your code.

`cargo check` is another useful command that analyzes your


source code and determines if it has any syntax or type errors
without actually building it. This works much faster than the `car-
go build` command because it does not create an executable
binary, which can save developers a significant amount of time
during the development process.

Building for release is an essential step in the deployment of a


Rust application. To optimize your code for better performance,
use the command `cargo build --release`. This prepares your
project with optimizations, creating a more efficient binary in the
“target/release” directory that is ideal for distribution.

63
Comments

1. Line Comments: Start line comments with `//` followed by


the explanation. Use line comments to describe a single line
of code or a specific part of an expression. Ensure they are
concise and direct.

Example:
```rust
let x = 5; // assigns value 5 to variable x
```

2. Block Comments: Enclose block comments between `/*`


and `*/`. Block comments should be used to add more de-
tailed descriptions that span multiple lines or to comment
out a block of temporary code.

64 Ascendance.dev
Comments
File name: main.rs

$ cargo run

65
Control Flow

Control flow refers to the order in which the code state-


ments are executed, allowing programmers to build con-
ditional branches, loops, and other structures to perform
tasks. In Rust, control flow elements primarily include if/else
if expressions, while loops, and for loops.

66 Ascendance.dev
Control Flow

• if/else if expressions
• while loops
• and for loops.
• for loops

67
If-else if expressions

1. If-else if expressions: These are used to execute code de-


pending on specific conditions. The if keyword is followed by
a condition, while the else-if keyword can be used to define
additional conditions if the previous conditions are not met.
If no conditions are met, the else keyword can be used to de-
fine a fallback action.

68 Ascendance.dev
If-else if expressions
File name: main.rs

$ cargo run

69
While loop

2. While loop: A while loop allows you to execute a block of


code repeatedly as long as the specified condition remains
true. The loop will continue until the condition is false or a
break statement is encountered.

70 Ascendance.dev
While loop
File name: main.rs

$ cargo run

71
For loop

3. For loop: Rust’s for loop is used to iterate over a collection


of items, such as arrays or ranges. It provides a more con-
venient and safer way to loop through items compared to a
while loop. You can use the for keyword followed by a vari-
able, the in keyword, and the collection you want to iterate
over.

72 Ascendance.dev
For loop
File name: main.rs

$ cargo run

73
This is the end of this journey there are advanced Rust concepts
and this book only is an intro, hope you find this useful, we focus a
lot on the learning experience.
Concepts like: borrowing, packages, crates, modules, tests, mod-
ules, lists, vectors, Strings, Error Handling, Generic Types, Traits,
Tests, Reading Files, I/O, and much more willbe covered on our
next book: “Intermediate Rust Programming”.
We are working hard to create advanced books in Rust!
Thanks for reading!
Protect Nature.
Rust Programming for Beginners Simpli-
fied Version ©

You might also like