Microsoft Rust Training

repository·main·Indexed 12 days ago

https://github.com/microsoft/rusttraining

A collection of seven specialized Rust training courses for developers of various backgrounds. Courses include language bridges for C++, C#, and Python, as well as deep dives into Async Rust, Rust Patterns, Type-Driven Correctness, and Rust Engineering Practices.

Tokens
413.8K
Snippets
952
Records
1.2K
Agent score
96%

What's inside Microsoft Rust Training

  1. Overview of the C# to Rust Training Curriculum

    main

    The C# to Rust training course is structured into 16 chapters designed to bridge the gap between C# and Rust. It covers fundamental language differences, memory management models, and practical ecosystem mappings.

    Curriculum Structure:

    • Foundations: Introduction, Motivation, Getting Started (including Keywords Reference), Built-in Types (including True Immutability), Control Flow, and Data Structures (including Collections).
    • Core Rust Concepts: Enums and Pattern Matching (including Null Safety), Ownership and Borrowing (including Memory Safety), Crates and Modules (including Package Management), and Error Handling.
    • Advanced Topics: Traits and Generics (including Inheritance vs Composition), From and Into Traits, Closures and Iterators, Concurrency, and Unsafe Rust/FFI.
    • Practical Application: Case Studies (Patterns, Essential Crates, and Adoption Strategies) and Best Practices.
  2. Overview of the C# to Rust Training Book Structure

    main

    The C# → Rust Training book is a structured guide designed to help developers transition from C# to Rust. It is organized into 16 chapters covering everything from basic syntax to advanced concurrency and migration strategies.

    Key learning areas include:

    • Foundations: Introduction, Getting Started (Installation, Cargo vs NuGet), and Built-in Types.
    • Core Rust Mechanics: Control Flow, Data Structures, Enums/Pattern Matching, and the critical Ownership and Borrowing model.
    • Advanced Features: Crates/Modules, Error Handling (Result vs Exceptions), Traits/Generics, and Concurrency.
    • Practical Transition: From/Into traits, Closures/Iterators (LINQ mapping), Unsafe Rust, and real-world Case Studies (Migration patterns, Essential Crates).
  3. Overview of Rust for C# Programmers Training Guide

    main

    This training guide is designed to help developers with C# experience transition to Rust. It focuses on conceptual shifts, practical differences, and mapping C# patterns to idiomatic Rust. The course is divided into three main parts:

    1. Foundations: Basic syntax, types, control flow, data structures, enums, ownership, modules, error handling, traits, and iterators.
    2. Concurrency & Systems: Thread safety, async/await (comparing Rust Future to C# Task), cancellation patterns, and Unsafe Rust/FFI.
    3. Migration & Best Practices: Real-world migration patterns, essential crates, and incremental adoption strategies.

    The guide uses difficulty indicators to help learners pace themselves:

    • 🟢 Beginner: Direct translation from C# concepts.
    • 🟡 Intermediate: Requires understanding ownership or traits.
    • 🔴 Advanced: Lifetimes, async internals, or unsafe code.
  4. Overview of Fourteen Tricks from the Trenches

    main

    This section introduces fourteen correct-by-construction techniques designed to eliminate specific bug classes in Rust with minimal effort. These techniques focus on using the type system to enforce correctness at boundaries and throughout the application lifecycle.

    Key concepts covered in this chapter include:

    • Sentinel elimination: Using Option at boundaries to replace sentinel values.
    • Sealed Traits: Restricting which types can implement a specific trait.
    • #[non_exhaustive]: Managing evolving enums to maintain backward compatibility.
    • Typestate Builder: Using types to represent the state of an object to prevent invalid operations.
    • FromStr as a Validation Boundary: Using the FromStr trait to ensure data is valid before it enters the system logic.
  5. Overview of Type-Driven Correctness Exercises

    main

    The exercises in this repository provide hands-on practice applying correct-by-construction patterns to realistic hardware scenarios. These exercises are designed to reinforce concepts learned in previous chapters of the 'Type-Driven Correctness' book.

    Key learning objectives include practicing with:

    • NVMe admin commands (Typed Commands)
    • Firmware update state machines (Type-State)
    • Sensor reading pipelines (Dimensional Analysis)
    • PCIe capability walks (Phantom Types + Validated Boundary)
    • Multi-protocol health checks
    • Session-typed diagnostic protocols
  6. Overview of Production Patterns in Async Rust

    main

    This section of the Rust training covers essential patterns for building robust, production-ready asynchronous applications. Key topics include:

    • Graceful Shutdown: Using watch channels and the select! macro to signal tasks to stop cleanly.
    • Backpressure: Implementing bounded channels to prevent Out-of-Memory (OOM) errors by limiting the number of pending tasks.
    • Structured Concurrency: Managing groups of tasks using JoinSet and TaskTracker to ensure tasks are tracked and completed.
    • Resiliency: Implementing timeouts, retries, and exponential backoff strategies.
    • Error Handling: Distinguishing between thiserror (for library errors) and anyhow (for application errors), and using the double-? pattern.
    • Middleware: Understanding the Tower service abstraction, which powers major frameworks like axum, tonic, and hyper.
  7. Course Curriculum Overview

    main

    The Rust Bootstrap Course for C/C++ Programmers covers the following topics:

    • Foundations: Types, functions, control flow, pattern matching, modules, and Cargo.
    • Core Rust Concepts: Traits, generics, collections, error handling, closures, memory management, lifetimes, and smart pointers.
    • Advanced Topics: Concurrency, Unsafe Rust, and Foreign Function Interface (FFI).
    • Specialized Content: no_std and embedded Rust essentials for firmware teams, and real-world C++ to Rust translation patterns.

    Note: This course does not cover async Rust. For futures, executors, Pin, tokio, and production async patterns, use the Async Rust Training companion course.

  8. Explore the Async Rust Book curriculum

    main

    The Async Rust Book is organized into three main parts to guide you from fundamental concepts to production-ready asynchronous programming:

    Part I: How Async Works

    Focuses on the core mechanics of Rust's async model, including:

    • Why async is unique in Rust
    • The Future trait
    • The poll mechanism
    • Pin and Unpin semantics
    • How the compiler transforms async code into state machines

    Part II: The Ecosystem

    Covers how to use async in real-world applications:\n- Building custom Future implementations

    • Understanding Executors and Runtimes
    • Deep dive into the Tokio runtime
    • Alternatives to Tokio
    • Working with Async Traits

    Part III: Production Async

    Focuses on advanced patterns and best practices:

    • Streams and AsyncIterator
    • Avoiding common pitfalls
    • Production-ready patterns
    • Understanding async as an optimization

    Appendices

    • Summary and Reference Card
    • Capstone Project: Building an Async Chat Server
  9. Compare Rust tooling to C# equivalents

    main

    If you are coming from a C# background, use this mapping to find familiar tools in the Rust ecosystem:

    C# ToolRust EquivalentInstall CommandPurpose
    Roslyn analyzersClippyrustup component add clippyLint + style suggestions
    dotnet formatrustfmtrustup component add rustfmtAuto-formatting
    XML doc commentscargo docBuilt-inGenerate HTML docs
    OmniSharp / Roslynrust-analyzerVS Code extensionIDE support
    dotnet watchcargo-watchcargo install cargo-watchAuto-rebuild on save
    cargo-expandcargo install cargo-expandSee macro expansion
    dotnet auditcargo-auditcargo install cargo-auditSecurity vulnerability scan
  10. Explore the C/C++ to Rust Training Curriculum

    main

    The c-cpp-book provides a structured learning path for C/C++ developers transitioning to Rust. The curriculum is divided into three main parts:

    1. Foundations: Covers core Rust concepts including Built-in Types, Control Flow, Data Structures, Enums, Ownership/Borrowing, Crates/Modules, Error Handling, Traits, Closures, Concurrency, and Unsafe Rust/FFI.
    2. Deep Dives: Focuses on advanced topics like no_std (Rust without the standard library) for embedded systems and real-world case studies of migrating C++ code to Rust.
    3. Best Practices & Reference: Provides guidance on idiomatic Rust, such as avoiding excessive .clone(), avoiding unchecked indexing, managing assignment pyramids, and using the logging/tracing ecosystem, as well as a deep dive into Rust macros.
  11. Summary of C++ to Rust translation patterns

    main

    This case study outlines five key architectural transformations used when migrating a large-scale C++ diagnostic system to Rust:

    #C++ PatternRust PatternImpact
    1Class hierarchy + dynamic_castEnum dispatch + match~400 → 0 dynamic_casts
    2shared_ptr / enable_shared_from_this treeArena + index linkageNo reference cycles
    3Framework* raw pointer in every moduleDiagContext<'a> with lifetime borrowingCompile-time validity
    4God objectComposable state structsTestable, modular
    5vector<unique_ptr<Base>> everywhereTrait objects only where neededStatic dispatch default
  12. Key takeaways from the Type-Safe Redfish Server walkthrough

    main

    This walkthrough demonstrates how to apply type-driven design to a Redfish server implementation to prevent common runtime errors. The core principles include:

    • Construct, don't serialize: Use the builder type-state pattern so that a .build() method is only available once all required fields are present, mirroring the "parse, don't validate" principle.
    • Source-availability tokens: Use capability tokens (similar to the pattern in Chapter 4) to prove that a data source has been properly initialized before use.
    • Dimensional types: Use distinct types for different units (e.g., Rpm vs ReadingCelsius) to ensure that producers and consumers cannot accidentally mix incompatible measurements.
    • Typed health rollups: Implement health status using Ord on a HealthValue type and explicit source references to ensure the compiler catches missing status updates (e.g., forgetting to include PSU status).
    • Type-level schema versioning: Use phantom type parameters to make version-specific fields appear or disappear at compile time.
    • Exhaustive action dispatch: Use serde to deserialize payloads into typed Params structs. By using exhaustive matching on enum variants (e.g., ResetType), adding a new variant will force all handlers to be updated, preventing unhandled actions.
    • Producer-side correctness: Prioritize compile-time correctness on the server (producer) side, as server-side bugs propagate to all connected clients.