Rust for C Programmers ★★★★☆
A Compact Introduction to the Rust Programming Language
© 2025 S. Salewski
Rust is a modern systems programming language designed for safety, performance, and efficient concurrency. As a compiled language, Rust produces optimized, native machine code, making it an excellent choice for low-level development. Rust enforces strong static typing, preventing many common programming errors at compile time. Thanks to robust optimizations and an efficient memory model, Rust also delivers high execution speed.
With its unique ownership model, Rust guarantees memory safety without relying on a runtime garbage collector. This approach eliminates data races and prevents undefined behavior while preserving performance. Rust’s zero-cost abstractions enable developers to write concise, expressive code without sacrificing efficiency. As an open-source project licensed under the MIT and Apache 2.0 licenses, Rust benefits from a strong, community-driven development process.
Rust’s growing popularity stems from its versatility, finding applications in areas such as operating systems, embedded systems, WebAssembly, networking, GUI development, and mobile platforms. It supports all major operating systems, including Windows, Linux, macOS, Android, and iOS. With active maintenance and continuous evolution, Rust remains a compelling choice for modern software development.
This book offers a compact yet thorough introduction to Rust, intended for readers with experience in systems programming. Those new to programming may find it helpful to begin with an introductory resource, such as the official Rust guide, ‘The Book’, or explore a simpler language before diving into Rust.
The online edition of the book is available at rust-for-c-programmers.com.
1.1 Why Rust?
Rust is a modern programming language that uniquely combines high performance with safety. Although concepts like ownership and borrowing can initially seem challenging, they enable developers to write efficient and reliable code. Rust’s syntax may appear unconventional to those accustomed to other languages, yet it offers powerful abstractions that facilitate the creation of robust software.
So why has Rust gained popularity despite its complexities?
Rust aims to balance the performance benefits of low-level systems programming languages with the safety, reliability, and user-friendliness of high-level languages. While low-level languages like C and C++ provide high performance with minimal resource usage, they can be prone to errors that compromise reliability. High-level languages such as Python, Kotlin, Julia, JavaScript, C#, and Java are often easier to learn and use but typically rely on garbage collection and large runtime environments, making them less suitable for certain systems programming tasks.
Languages like Rust, Go, Swift, Zig, Nim, Crystal, and V seek to bridge this gap. Rust has been particularly successful in this endeavor, as evidenced by its growing adoption.
As a systems programming language, Rust enforces memory safety through its ownership model and borrow checker, preventing issues such as null pointer dereferencing, use-after-free errors, and buffer overflows—all without using a garbage collector. Rust avoids hidden, expensive operations like implicit type conversions or unnecessary heap allocations, giving developers precise control over performance. Copying large data structures is typically avoided by using references or move semantics to transfer ownership. When copying is necessary, developers must explicitly request it using methods like clone(). Despite these performance-focused constraints, Rust provides convenient high-level features such as iterators and closures, offering a user-friendly experience while retaining high efficiency.
Rust’s ownership model also guarantees fearless concurrency by preventing data races at compile time. This simplifies the creation of concurrent programs compared to languages that might detect such errors only at runtime—or not at all.
Although Rust does not employ a traditional class-based object-oriented programming (OOP) approach, it incorporates OOP concepts via traits and structs. These features support polymorphism and code reuse in a flexible manner. Instead of exceptions, Rust uses Result and Option types for error handling, encouraging explicit handling and helping to avoid unexpected runtime failures.
Rust’s development began in 2006 with Graydon Hoare, initially supported by volunteers and later sponsored by Mozilla. The first stable version, Rust 1.0, was released in 2015. By version 1.86 and the Rust 2024 edition (stabilized in late 2024), Rust had continued to evolve while maintaining backward compatibility. Today, Rust benefits from a large, active developer community. After Mozilla reduced its direct involvement, the Rust community formed the Rust Foundation, supported by major companies like AWS, Google, Microsoft, and Huawei, among others, to ensure the language’s continued growth and sustainability. Rust is free, open-source software licensed under the permissive MIT and Apache 2.0 terms for its compiler, standard library, and most external packages (crates).
Rust’s community-driven development process relies on RFCs (Requests for Comments) to propose and discuss new features. This open, collaborative approach has fueled Rust’s rapid evolution and fostered a rich ecosystem of libraries and tools. The community’s emphasis on quality and cooperation has turned Rust from merely a programming language into a movement advocating for safer, more efficient software development practices.
Well-known companies such as Meta (Facebook), Dropbox, Amazon, and Discord utilize Rust for various projects. Dropbox, for instance, employs Rust to optimize its file storage infrastructure, while Discord leverages it for high-performance networking components. Rust is widely used in system programming, embedded systems, WebAssembly development, and for building applications on PCs (Windows, Linux, macOS) and mobile platforms. A significant milestone is Rust’s integration into the Linux kernel—the first time an additional language has been adopted alongside C for kernel development. Rust is also gaining momentum in the blockchain industry.
Rust’s ecosystem is mature and well-supported. It features a powerful compiler (rustc), the modern Cargo build system and package manager, and Crates.io, an extensive repository of open-source libraries. Tools like rustfmt for automated code formatting and clippy for static analysis (linting) help maintain code quality and consistency. The ecosystem includes modern GUI frameworks like EGUI and Xilem, game engines such as Bevy, and even entire operating systems like Redox-OS, all developed in Rust.
As a statically typed, compiled language, Rust historically might not have seemed the primary choice for rapid prototyping, where dynamically typed, interpreted languages (e.g., Python or JavaScript) often excel. However, Rust’s continually improving compile times—aided by incremental compilation and build artifact caching—combined with its robust type system and strong IDE support, have made prototyping in Rust increasingly efficient. Many developers now choose Rust for projects from the outset, valuing its performance, safety guarantees, and the smoother transition from prototype to production-ready code.
Since this book assumes familiarity with the motivations for using Rust, we will not delve further into analyzing its pros and cons. Instead, we will focus on its core features and its established ecosystem. The LLVM-based compiler (rustc), the Cargo package manager, Crates.io, and Rust’s vibrant community are essential factors contributing to its growing importance.
1.2 What Makes Rust Special?
Rust stands out primarily by offering automatic memory management without a garbage collector. It achieves this through strict compile-time rules governing ownership, borrowing, and move semantics, along with making immutability the default (variables must be explicitly declared mutable with mut). Rust’s memory model ensures excellent performance while preventing common issues like invalid memory access or data races. Its zero-cost abstractions enable the use of high-level programming constructs without runtime performance penalties. Although this system requires developers to pay closer attention to memory management concepts, the long-term benefits—improved performance and fewer memory-related bugs—are particularly valuable in large or critical projects.
Here are some of the key features that distinguish Rust:
1.2.1 Error Handling Without Exceptions
Rust eschews traditional exception handling mechanisms (like try/catch). Instead, it employs the Result and Option enum types for representing success/failure or presence/absence of values, respectively. This approach mandates that developers explicitly handle potential error conditions, preventing situations where failures might be silently ignored. Such unhandled errors are a common problem when exceptions raised deep within a call stack remain uncaught during development, potentially leading to unexpected program crashes in production. While explicit error handling can sometimes lead to more verbose code, the ? operator provides a concise syntax for propagating errors upward, maintaining readability. Rust’s error-handling strategy fosters more predictable and transparent code.
1.2.2 A Different Approach to Object-Oriented Programming
Rust incorporates object-oriented concepts like encapsulation and polymorphism but does not support classical inheritance. Instead, Rust favors composition over inheritance and utilizes traits to define shared behaviors and interfaces. This results in flexible and reusable code designs. Through trait objects, Rust supports dynamic dispatch, enabling polymorphism comparable to that found in traditional OOP languages. This design encourages clear, modular code while avoiding many complexities associated with deep inheritance hierarchies. For developers familiar with Java interfaces or C++ abstract classes, Rust’s traits offer a powerful and modern alternative.
1.2.3 Powerful Pattern Matching and Enumerations
Rust’s enumerations (enums) are significantly more powerful than those found in many other languages. They are algebraic data types, meaning each variant of an enum can hold different types and amounts of associated data. This makes them exceptionally well-suited for modeling complex states or data structures. When combined with Rust’s comprehensive pattern matching capabilities (using match expressions), developers can write concise and expressive code to handle various cases exhaustively and safely. Although pattern matching might seem unfamiliar at first, it greatly simplifies working with complex data types and enhances code readability and robustness.
1.2.4 Safe Threading and Parallel Processing
Rust excels at enabling safe concurrency and parallelism. Its ownership and borrowing rules are enforced at compile time, effectively eliminating data races—a common source of bugs in concurrent programs. This compile-time safety net gives rise to Rust’s concept of fearless concurrency, allowing developers to build multithreaded applications with greater confidence, as the compiler flags potential data race conditions or synchronization errors before runtime. Libraries like Rayon provide simple, high-level APIs for data parallelism, making it straightforward to leverage multi-core processors for performance-critical tasks. This makes Rust an appealing choice for applications demanding both high performance and safe concurrency.
1.2.5 Distinct String Types and Explicit Conversions
Rust primarily uses two distinct types for handling strings: String and &str. String represents an owned, mutable, heap-allocated string buffer, whereas &str (a “string slice”) is an immutable borrowed view into string data, often used for string literals or substrings. Although managing these two types can initially be confusing for newcomers, Rust’s strict distinction clarifies ownership and borrowing semantics, ensuring memory safety when working with text. Conversions between these types generally require explicit function calls (e.g., String::from("hello"), my_string.as_str()) or trait-based conversions (using Into, From, or AsRef). While this explicitness can introduce some verbosity compared to languages with implicit string conversions, it enhances performance predictability, clarity, and safety by making ownership transfers and borrowing explicit.
Similarly, Rust demands explicit type conversions (casting) between numeric types (e.g., using as f64, as i32). Integers do not automatically convert to floating-point numbers, and vice versa. This strict approach helps prevent subtle errors related to precision loss or unexpected behavior and avoids potential performance overhead from implicit conversions.
1.2.6 Trade-offs in Language Features
Rust intentionally omits certain convenience features found in other languages. For instance, it lacks native support for default function parameters or named function parameters, though the latter is a frequently discussed potential addition. Rust also does not have built-in subrange types (like 1..100 as a distinct type) or dedicated type or constant definition sections as seen in languages like Pascal, which can sometimes make Rust code organization appear slightly more verbose. However, developers commonly employ design patterns like the builder pattern or method chaining to simulate optional or named parameters effectively, often resulting in clear and maintainable APIs. The Rust community actively discusses potential language additions, balancing convenience with the language’s core principles of safety and explicitness.
1.3 About the Book
Several excellent and thorough Rust books already exist. Notable examples include the official guide, The Book, and more comprehensive works such as Programming Rust, 2nd Edition by Jim Blandy, Jason Orendorff, and Leonora F. S. Tindall. For those seeking deeper insights, Rust for Rustaceans by Jon Gjengset and the online resource Effective Rust are highly recommended. Additional practical resources include Rust by Example, 100 Exercises To Learn Rust and the Rust Cookbook. Numerous video tutorials are also available for visual learners.
Amazon lists many other Rust books, but assessing their quality beforehand can be challenging. Some may offer valuable content, while others might contain trivial information, potentially generated by AI without sufficient review or simply repurposed from free online sources.
Given this abundance of material, one might reasonably ask: why write another Rust book? Traditionally, creating a high-quality technical book demands deep subject matter expertise, strong writing skills, and a significant time investment—often exceeding a thousand hours. Professional editing and proofreading by established publishers have typically been crucial for eliminating errors, ensuring clarity, and producing a text that is genuinely useful and enjoyable to read.
Some existing Rust books tend towards verbosity, perhaps over-explaining certain concepts. Books focusing purely on Rust, written in concise, professional technical English, are somewhat less common. This might be partly because Rust is a complex language with several unconventional concepts (like ownership and borrowing). Authors often try to compensate by providing elaborate explanations, sometimes adopting a teaching style better suited for absolute beginners rather than experienced programmers transitioning from other languages. Therefore, a more compact, focused book tailored to this audience could be valuable, though whether the effort required is justified remains debatable.
However, the landscape of technical writing has changed significantly, especially over the last couple of years, due to the advent of powerful AI tools. These tools can substantially reduce the workload involved. Routine yet time-consuming tasks like checking grammar and spelling—often a hurdle for non-native English speakers—can now be handled reliably by AI. AI can also assist in refining writing style, for example, by breaking down overly long sentences, reducing wordiness, or removing repetitive phrasing. Beyond editing, AI can help generate initial drafts for sections, suggest relevant content additions, assist in reorganizing material, propose code examples, or identify redundancies. While AI cannot yet autonomously write a complete, high-quality book on a complex subject like Rust, an iterative process involving AI assistance combined with careful human oversight, review, and expertise can save a considerable amount of time and effort.
One of the most significant benefits lies in grammar correction and style refinement, tasks that can be particularly tedious and error-prone for authors writing in a non-native language.
This book project began in September 2024 partly as an experiment: could AI assistance make it feasible to produce a high-quality Rust book without the traditional year-long (or longer) commitment? The results have been promising, suggesting that the total effort can be reduced significantly, perhaps by around half. For native English speakers with strong writing skills, the time savings might be less dramatic but still substantial.
Some might argue for waiting a few more years until AI potentially reaches a stage where it can generate complete, high-quality, and perhaps even personalized books on demand. We believe that future is likely not too distant. However, with this book now nearing completion, the hundreds of hours already invested have yielded a valuable result.
This book primarily targets individuals with existing systems programming experience—those familiar with statically typed, compiled languages such as C, C++, D, Zig, Nim, Ada, Crystal, or similar. It is not intended as a first introduction to programming. Readers whose primary experience is with dynamically typed languages like Python might find the official Rust book or other resources tailored to that transition more suitable.
Our goal is to present Rust’s fundamental concepts as succinctly as possible. We aim to avoid unnecessary repetition, overly lengthy theoretical discussions, and extensive coverage of basic programming principles or computer hardware fundamentals. The focus is on core Rust language features (initially excluding advanced topics like macros and async programming in full depth) within a target length of fewer than 500 pages. Consequently, we limit the inclusion of deep dives into niche topics or very large, complex code examples. We believe that exhaustive detail on every minor feature is less critical today, given the ready availability of Rust’s official documentation, specialized online resources, and capable AI assistants for answering specific queries. Most readers do not need to memorize every nuance of features they might rarely encounter.
The title Rust for C Programmers reflects this objective: to provide an efficient pathway into Rust for experienced developers, particularly those coming from a C or C++ background.
Structuring a book about a language as interconnected as Rust presented challenges. We have attempted to introduce Rust’s most compelling and practical features relatively early, while acknowledging the inherent dependencies between different concepts. Although reading the chapters sequentially is generally recommended, they are not so tightly coupled as to make out-of-order reading impossible—though you might occasionally encounter forward or backward references.
We’ve aimed to minimize repeating the same concepts across multiple chapters to keep the content engaging and to make efficient use of space, especially in a printed format. That said, some overlap is unavoidable because many of Rust’s features are deeply interconnected. In fact, a bit of repetition can be helpful, reinforcing key ideas and supporting the learning process. Trying to eliminate repetition entirely would require a rigid chapter structure, making it difficult for readers to jump around the book. Some repetition is by design—for instance, Chapter 2 offers a quick overview of Rust’s core concepts to give readers an early sense of the language and lay a foundation for later chapters. Similarly, Chapters 3 and 4 cover installation and basic compiler usage early on, since they’re essential, but we’ve kept these sections concise to stay focused on learning the language itself. More in-depth topics like Cargo are saved for Chapter 23, and for OS-specific installation details, we direct readers to Rust’s official online documentation.
When viewing the online version of this book (generated using the mdbook tool), you can typically select different visual themes (e.g., light/dark) from a menu and utilize the built-in search functionality. If the default font size appears too small, most web browsers allow you to increase the page zoom level (often using ‘Ctrl’ + ‘+’). Code examples containing lines hidden for brevity can usually be expanded by clicking on them. Many examples include a button to run the code directly in the Rust Playground. You can also modify the examples in place before running them, or simply copy and paste the code into the Rust Playground website yourself. We recommend reading the online version in a web browser equipped with a persistent text highlighting tool or extension (such as the ‘Textmarker’ addon for Firefox or similar tools for other browsers), which can be helpful for marking important sections. Most modern browsers also offer the capability to save web pages for offline viewing. Additionally, mdbook can optionally be used to generate a PDF version of the entire book. Other formats like EPUB or MOBI for dedicated e-readers are not currently supported by the standard tooling.
Whether a printed version of this book will be published remains undecided. Printed computer books tend to become outdated relatively quickly, and the costs associated with publishing, printing, and distribution might consume a significant portion of potential revenue. On the other hand, making the book available through platforms like Amazon could be an effective way to reach a wider audience.
1.4 About the Authors
The principal author, Dr. S. Salewski, studied Physics, Mathematics, and Computer Science at the University of Hamburg (Germany), receiving his Ph.D. in experimental laser physics in 2005. His professional experience includes research on fiber lasers, electronics design, and software development using various languages, including Pascal, Modula-2, Oberon, C, Ruby, Nim, and Rust. Some of his open-source projects—such as GTK GUI bindings for Nim, Nim implementations of an N-dimensional R-Tree index, and a fully dynamic constrained Delaunay triangulation algorithm—are available on GitHub at https://github.com/StefanSalewski. This repository also hosts a Rust port of his simple chess engine (with GTK, EGUI, and Bevy frontends), selected chapters of this book in Markdown format, and materials for another online book by the author about the Nim programming language, published in 2020.
Naturally, much of the factual content and conceptual explanations in this book draw upon the wealth of resources created by the Rust community. This includes numerous existing books, the official online Rust Book, Rust’s language reference and standard library documentation, Rust-by-Example, the Cargo Book, the Rust Performance Book, blog posts, forum discussions, and many other sources.
As mentioned previously, this book was written with significant assistance from Artificial Intelligence (AI) tools. In the current era of technical publishing, deliberately avoiding AI would be highly inefficient and likely counterproductive, potentially even resulting in a lower-quality final product compared to what can be achieved with AI augmentation. Virtually all high-quality manufactured goods we use daily are produced with the aid of sophisticated tools and automation; applying similar principles to the creation of a programming book seems logical.
Initially, we considered listing every AI tool used, but such a list quickly became impractical. Today’s large language models (LLMs) possess substantial knowledge about Rust and can generate useful draft text, perform sophisticated grammar and style refinements, and answer specific technical questions. For the final editing phases of this book, we primarily utilized models such as OpenAI’s ChatGPT o1 and Google’s Gemini 2.5 Pro. These models proved particularly adept at creating concise paraphrases and improving clarity, sometimes suggesting removal of the author’s original text if it was deemed too verbose or tangential. Through interactive prompting via paid subscriptions to these services, we guided the AI towards maintaining a concise, neutral, and professional technical style throughout the final iterations, ensuring a coherent and consistent presentation across the entire book.