Skip to content

Commit

Permalink
pointers and others
Browse files Browse the repository at this point in the history
  • Loading branch information
saltukalakus committed Nov 10, 2024
1 parent 79d1cc0 commit 8bb5407
Show file tree
Hide file tree
Showing 8 changed files with 216 additions and 3 deletions.
4 changes: 4 additions & 0 deletions src/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,15 @@
- [Feature Attribute](./essentials/packaging/feature-attribute.md)
- [Features Compilation](./essentials/packaging/features-compilation.md)
- [Types](./essentials/types/intro.md)
- [Scalar Types](./essentials/types/scalar.md)
- [Compound Types](./essentials/types/compound.md)
- [Traits](./essentials/types/trait.md)
- [Structs](./essentials/types/struct.md)
- [Enums](./essentials/types/enum.md)
- [Structs vs Enums](./essentials/types/struct-vs-enums.md)
- [Generics](./essentials/types/generics.md)
- [Type Alias](./essentials/types/type-alias.md)
- [Pointers](./essentials/types/pointer.md)
- [Standard Library](./essentials/std-lib/intro.md)
- [Self Keyword](./essentials/std-lib/self.md)
- [Imp Keyword](./essentials/std-lib/imp.md)
Expand Down
4 changes: 3 additions & 1 deletion src/essentials/packaging/intro.md
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
# packaging
### Packing and related topics

This section contains random information about Cargo and various other bits and pieces on building a Rust project.
4 changes: 3 additions & 1 deletion src/essentials/std-lib/intro.md
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
# Standard Library
### Standard Library

This section explains some of the command standard library APIs and their usage. The intention is not to cover the entire API.
21 changes: 21 additions & 0 deletions src/essentials/types/compound.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
### Compound Types

Compound types can group multiple values into one type. Rust has two primary compound types:

Tuples: Group multiple values of different types.<br/>
Arrays: Group multiple values of the same type.<br/>

Example:

```rust
fn main() {
// Tuple
let tuple: (i32, f64, char) = (42, 3.14, 'A');
let (x, y, z) = tuple;
println!("Tuple: ({}, {}, {})", x, y, z);

// Array
let array: [i32; 3] = [1, 2, 3];
println!("Array: {:?}", array);
}
```
10 changes: 9 additions & 1 deletion src/essentials/types/intro.md
Original file line number Diff line number Diff line change
@@ -1 +1,9 @@
# Types
### Types

Types in Rust are a way to define the kind of data that can be stored and manipulated within a program. Rust is a statically typed language, which means that the type of every variable must be known at compile time. This helps catch many errors early in the development process and ensures memory safety.

### Categories of Types in Rust

[**Scalar Types**](./scalar.md): Represent a single value.<br/>
[**Compound Types**](./compound.md): Group multiple values into one type.<br/>
**User-Defined Types**: Custom types defined by the user such as [struct](./struct.md) and [enum](./enum.md).<br/>
73 changes: 73 additions & 0 deletions src/essentials/types/pointer.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
### What is pointers and how they are used in Rust?

In Rust, pointers are types that represent memory addresses. Rust provides several types of pointers, each with different characteristics and use cases. Pointers are used to reference data stored in memory, and Rust's ownership and borrowing rules ensure that pointers are used safely.

### Types of Pointers in Rust

**References**: Immutable and mutable references.<br/>
**Smart Pointers**: Box, Rc, Arc, and others.<br/>
**Raw Pointers**: Unsafe pointers.<br/>

### References

References are the most common type of pointer in Rust. They allow you to borrow data without taking ownership. There are two types of references:

Immutable References (`&T`): Allow you to read data but not modify it.<br/>
Mutable References (`&mut T`): Allow you to modify data.<br/>

```rust
fn main() {
let x = 5;
let y = &x; // Immutable reference
println!("y: {}", y);

let mut z = 10;
let w = &mut z; // Mutable reference
*w += 5;
println!("z: {}", z);
}
```

### Smart Pointers

Smart pointers are data structures that not only act like a pointer but also have additional capabilities, such as automatic memory management. Common smart pointers in Rust include:

**Box**: A heap-allocated pointer.<br\>

```rust
fn main() {
let b = Box::new(5);
println!("b: {}", b);
}
```

**Rc**: A reference-counted pointer for single-threaded scenarios.<br\>

```rust
use std::rc::Rc;

fn main() {
let a = Rc::new(5);
let b = Rc::clone(&a);
println!("a: {}, b: {}", a, b);
}
```

**Arc**: An atomic reference-counted pointer for multi-threaded scenarios.<br\>

```rust
use std::sync::Arc;
use std::thread;

fn main() {
let a = Arc::new(5);
let b = Arc::clone(&a);

let handle = thread::spawn(move || {
println!("b: {}", b);
});

println!("a: {}", a);
handle.join().unwrap();
}
```
22 changes: 22 additions & 0 deletions src/essentials/types/scalar.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
### Scalar Types

Scalar types represent a single value. Rust has four primary scalar types:

**Integers**: Whole numbers, both signed and unsigned.<br/>
**Floating-Point Numbers**: Numbers with decimal points.<br/>
**Booleans**: True or false values.<br/>
**Characters**: Single Unicode characters.<br/>

Example:

```rust
fn main() {
let x: i32 = 42; // Integer
let y: f64 = 3.14; // Floating-point number
let is_active: bool = true; // Boolean
let letter: char = 'A'; // Character

println!("x: {}, y: {}, is_active: {}, letter: {}", x, y, is_active, letter);
}
```

81 changes: 81 additions & 0 deletions src/essentials/types/type-alias.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
# What is type alias in Rust?

In Rust, a type alias allows you to create a new name for an existing type. This can make your code more readable and easier to manage, especially when dealing with complex types. Type aliases are created using the `type` keyword.

### Benefits of Type Aliases

Improved Readability: By giving a meaningful name to a type, you can make your code more understandable. <br/>
Simplified Code: Type aliases can simplify complex type signatures, making the code easier to write and read.<br/>
Consistency: Using type aliases can help maintain consistency across your codebase.
Syntax<br/>


The syntax for creating a type alias is:

```rust,noplaypen
type NewName = ExistingType;
```
Example: Basic type alias

Here is a simple example of using a type alias to rename an existing type:

```rust
type Kilometers = i32;

fn main() {
let distance: Kilometers = 100;
println!("Distance: {} km", distance);
}
```

In this example, `Kilometers` is a type alias for `i32`. This makes it clear that the distance variable represents a distance in kilometers.

Example: Using type aliases with [structs](./struct.md)

```rust
struct Point<T> {
x: T,
y: T,
}

type IntPoint = Point<i32>;
type FloatPoint = Point<f64>;

fn main() {
let int_point: IntPoint = Point { x: 5, y: 10 };
let float_point: FloatPoint = Point { x: 1.0, y: 4.0 };

println!("IntPoint: ({}, {})", int_point.x, int_point.y);
println!("FloatPoint: ({}, {})", float_point.x, float_point.y);
}
```
In this example, `IntPoint` and `FloatPoint` are type aliases for `Point<i32>` and `Point<f64>`, respectively. This makes it clear what type of points are being used.


Example: Complex type alias

Type aliases are particularly useful for complex types, such as function pointers or nested types. Here is an example:

```rust
type Thunk = Box<dyn Fn() + Send + 'static>;

fn takes_long_type(f: Thunk) {
// Do something with the function
}

fn returns_long_type() -> Thunk {
Box::new(|| println!("Hello, world!"))
}

fn main() {
let f: Thunk = returns_long_type();
takes_long_type(f);
}
```

In this example,`type Thunk = Box<dyn Fn() + Send + 'static>;` creates a type alias named Thunk.<br/>
**Box**: Box is a smart pointer that allocates data on the heap.<br/>
**dyn Fn()**: dyn Fn() is a trait object representing a closure that takes no arguments and returns nothing.<br/>
**Send**: The Send trait indicates that the closure can be transferred across thread boundaries.<br/>
**'static**: The 'static lifetime means that the closure can live for the entire duration of the program.<br/>

0 comments on commit 8bb5407

Please sign in to comment.