sprtd
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee
    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee
  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # Rust Sessions #### Why Rust - Built-in multi-threading system - Type-system - uncover bugs at compile time - module system that simplifies code separation - Robust tooling for docs generation, code linting and code auto formatting - In summary, Rust maintains a significant balance between speed, safety, concurrency and portability - Compilation to machine code is pretty fast - Uses ownership for memory management Primitive/Scalar Data Types - Bool - Float - Integers #### Data types: - Memory only stores binary data - anything can be represented in binary - Generally, programs determine what binary represents - - Primitives: - boolean - true || false - floating point - 2.5, 0.7 - char - '7' - integers: - signed (i) - unsigned (u) - strings - "gm" # Rust Notes #### 04-02-24 In Rust, both String and str are related to handling text, but they have different meanings and use cases. `String`: This is a heap-allocated, growable, UTF-8 encoded string type. It is part of the standard library and is owned, meaning it has ownership semantics and can be mutable. You can manipulate it dynamically, and it is suitable for situations where you need to modify or grow the string at runtime. Example ```rs= let my_string = String::from("Hello, "); let other_string = String::from("world!"); let combined_string = my_string + &other_string; println!("{}", combined_string); ``` In this example, `String::from` creates a new String, and the + operator is used to concatenate two strings, taking ownership of the first one. `str`: This is a string slice, which is an immutable view into a string. It is a reference to a sequence of UTF-8 bytes and is often used when you want to work with strings without taking ownership. str is a primitive type in Rust and is often seen as the borrowed form of a string. Example: `let my_str: &str = "Hello, world!";` In this example, `my_str` is a reference to a string slice. In summary, String is a heap-allocated, growable, owned string type, while str is an immutable reference to a sequence of UTF-8 bytes. String is more flexible for dynamic string manipulation, while str is commonly used when you want to work with string data without taking ownership. #### Why `&` in string ```rust= let my_string = String::from("Hello, "); let other_string = String::from("world!"); let combined_string = my_string + &other_string; println!("{}", combined_string); ``` The `&` in `&other_string` is used to take a reference to `other_string` rather than taking ownership of it. The + operator in Rust is implemented to take ownership of its operands. However, the & before other_string creates a reference to it, allowing the + operator to borrow the content of other_string without taking ownership. If you were to omit the &, the ownership of `other_string` would be transferred to `my_string`, and you wouldn't be able to use `other_string` afterward: ```rust= let my_string = String::from("Hello, "); let other_string = String::from("world!"); let combined_string = my_string + other_string; // Error: value moved println!("{}", combined_string); // other_string is now inaccessible because its ownership was transferred to combined_string ``` ``` rs= fn main() { let owned_string = String::from("Hello, world!"); // Creates an owned String let moved_string = transfer_ownership(owned_string); // owned_string is no longer accessible here because its ownership was moved println!("{}", moved_string); } fn transfer_ownership(s: String) -> String { println!("Ownership transferred: {}", s); s // Return ownership } ``` #### Hey! Why not add `&` to `my_string`? In Rust, the + operator for string concatenation expects the left operand to be a String and the right operand to be a &str. The & is automatically added to the String on the right side of the + operator by the Rust compiler through a mechanism called "Deref coercion" and "Borrow coercion." `let combined_string = my_string + &other_string;` The `&other_string` is automatically converted to a &str reference to its content, and the + operator is then able to concatenate a String with a `&str`. This is a convenient and ergonomic feature of Rust. If you were to explicitly add & to my_string, it would result in a type error, because the + operator requires a String on the left side: ```rust= let combined_string = &my_string + &other_string; // Error: mismatched types ``` So, the compiler automatically handles the borrowing and coercion for you in this specific context. #### What is the difference between the above concatenation approach with using format macro to concat? Using the + operator for string concatenation and the format! macro are two different approaches to building strings in Rust. Here are the key differences: Ownership and Mutation: + Operator: It takes ownership of its operands. If you concatenate two String instances using +, the ownership of the left operand is transferred to the result, and the left operand cannot be used afterward unless it is cloned. format! Macro: It creates a new String without taking ownership of its arguments. The original values are not modified or moved. Flexibility: + Operator: It's more concise and can be convenient for simple concatenation operations. However, it can be less flexible for complex formatting tasks or when working with different types. format! Macro: It provides more flexibility and control over the formatting of strings. You can include various types, expressions, and format specifiers within the macro, making it suitable for more complex string building. Here's an example to illustrate the differences: Using + operator: ```rust= let name = String::from("John"); let greeting = "Hello, " + &name; // ownership of name transferred to greeting // name is no longer valid here ``` Using format! macro: ```rust= let name = String::from("John"); let greeting = format!("Hello, {}", name); // name is still valid here, as format! does not take ownership ``` In general, if you need simple concatenation and are comfortable with ownership transfer, the + operator might be more concise. If you require more complex formatting or want to keep ownership of the original values, the format! macro is often a more suitable choice. Resources: 1. https://medium.com/israeli-tech-radar/rust-stack-and-heap-moves-and-copies-104b3146b977#:~:text=The%20stack%20and%20the%20heap%20in%20Rust&text=As%20such%2C%20they%20are%20abstractions,memory%20allocation%20size%20is%20unknown. 2. https://web.mit.edu/rust-lang_v1.25/arch/amd64_ubuntu1404/share/doc/rust/html/book/first-edition/the-stack-and-the-heap.html # Understanding Ownership in Rust - Ownership model is a way to manage memory ## WTF is Ownership - Data structure/variable responsible for allocating and freeing the memory used to store value/data ## Ownership Rules - Each value in Rust has an owner. - There can only be one owner at a time. - When the owner goes out of scope, the value will be dropped. - https://doc.rust-lang.org/book/ch04-01-what-is-ownership.html ## WTF is Memory - Component in a computer that stores data and instructions for the processor to execute ## 🚗 Manual vs. Automatic Cars — Memory Management Analogy | Concept | Manual Car (C, C++) | Automatic Car (Rust) | | ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | | **Gear Shifting** | You (the programmer) have full control and responsibility for shifting gears (allocating and freeing memory). | The car (compiler) shifts gears for you automatically (memory is managed via ownership, borrowing, and lifetimes). | | **Stalling Risk** | High — if you forget to deallocate memory or free it twice, the program crashes (memory leaks, undefined behavior). | Low — Rust prevents stalls by enforcing rules at compile time (e.g., use-after-free, double free, data races are compile-time errors). | | **Clutch Mastery (e.g., `malloc`/`free`)** | You need to master the clutch to drive smoothly. You call `malloc` and `free` and must get it *just right*. | No clutch to worry about — Rust handles memory cleanly and safely using its ownership system. | | **Engine Control** | You have access to all internals — which is powerful but dangerous. | Rust still gives you access to internals (unsafe blocks), but wraps most behavior in safe abstractions. | | **Driver Responsibility** | You're responsible for every aspect of memory. One small mistake, and the system misbehaves. | You're guided by the compiler to write safe and correct code. Mistakes are caught early, before runtime. | | **Advanced Features** | Manual gives you more control and is better for fine-tuned performance. | Rust offers both: the ease of automatic with optional manual overrides (`unsafe`), without sacrificing performance. | 🧠 Memory-Specific Comparison C/C++ (Manual Car): You must manage when and how memory is allocated and freed. Forgetting to free memory leads to leaks. Freeing too early leads to dangling pointers. Access from multiple threads leads to data races unless you're extra careful. Rust (Automatic Car): Memory is freed automatically when it goes out of scope — thanks to the ownership model. You can’t access freed memory — the borrow checker stops you at compile time. No garbage collector, but still automatic — performance remains close to C/C++. Thread safety is baked into the type system — data races are compile-time errors. 🛠️ Bonus: C# as a Semi-Automatic Car If you're bringing C# into the analogy: Think of C# as a semi-automatic car. You don’t have to manage memory directly (new allocates, GC cleans up). But garbage collection can pause your app (GC pauses), and you don't control when it happens. Rust gives you deterministic cleanup without a GC, like a car that knows exactly when to shift gears. 🎯 Key Takeaway "Rust gives you the control of a manual with the safety and ease of an automatic — without ever stalling the engine." This analogy helps students appreciate why Rust is safer than C/C++ and more predictable than garbage-collected languages like C# or Java, all while remaining close to the metal. | Current Solutions for Managing Memory | Pros | Cons | |----------|----------|----------| | Garbage collection | <li>Error free</li><li>Faster write time</li> | <li>no control over memory</li><li>slower/unpredictable runtime performance</li> <li>larger program size</li> | | Manual Memory Management | <li>control over memory</li><li>faster run time</li><li>smaller program size</li> |<li>Error prone</li><li>slower write time</li> | | Ownership Model | <li>full control over memory</li><li>error free</li><li>faster run time</li><li>smaller program size</li> | <li>slower write time</li><li>steep learning curve</li> - Deep dive into stack and heap - https://web.mit.edu/rust-lang_v1.25/arch/amd64_ubuntu1404/share/doc/rust/html/book/first-edition/the-stack-and-the-heap.html ### Bash Scripting https://www.youtube.com/watch?v=tK9Oc6AEnR4

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully