Showing posts with label rust. Show all posts
Showing posts with label rust. Show all posts

Tuesday

Unsafe Rust vectors

Here's the unsafe Rust vectors program that implements a vector Vec template with the <String> data type.
This program demonstrates the use of Vec<String> to store a collection of strings.
The push and pop methods are used to add and remove elements from the vector.
Indexing is used to access specific elements within the vector.
The {:?} format specifier is used to print the value of a variable in a readable format.

This Rust program is unsafe and has out-of-bounds access.
If the index 3 is out of bounds. i.e., if the vector has fewer than four elements, accessing people_names[3] would result in undefined behavior, potentially leading to memory errors or crashes.

To have safe alternative, you can achieve the same functionality using safe Rust constructs. For example, you could use the get() method on the vector to safely access elements, which returns an Option to handle out-of-bounds case.


fn main() {

    let mut people_names : Vec<String> = Vec::new();

    people_names.push("Person_Name_01".to_string());

    people_names.push("Person_Name_02".to_string());

    people_names.push("Person_Name_03".to_string());

    people_names.push("Person_Name_04".to_string());


    people_names.pop();


          // index out of bounds: the len is 3 but the index is 3

    let fourth = &people_names[3];

    println!("Fourth person is {:?}", fourth);

}

Saturday

Unsafe Rust, Rust pointers

One reason unsafe Rust exists because the underlying computer hardware is inherently unsafe.
Other reason, Rust needs to allow programmer to interact with the operating system.
Other goal of the Rust programming language to allow software engineer to work with low-level programming.

Rust has type called pointer.
Programmers can create pointers.
Use "as" to cast a reference mutable variable into their corresponding pointer type.
Change or print pointers in the unsafe block.

Example: Rust pointers
Here's the Rust program that implements a pointer using reference ampersand symbol for mutable keyword, variable name, "as" casting, pointer asterisk symbol for mutable keyword again, and data type name.

fn main() {

    let mut i = 10;

    let ptr_to_i = &mut i as *mut i32;

   

    unsafe {

        *ptr_to_i = 20;

        println!("*ptr_to_i: {}", *ptr_to_i);

    }    


    // variable i is changed by the pointer

    println!("i: {}", i);

}

Rust cargo to create new project and run project in short

Rust cargo command to create new project and run project in short
> cargo new rust_cargo_0X_project_name

> cd rust_cargo_0X_project_name

> cargo run

Question: Can you draw a square with three lines?

A teacher asked students to draw a square with 3 lines.