Rust for C++ programmers

Overview

Rust For Systems Programmers

A Rust tutorial for experienced C and C++ programmers.

Jump to contents. Jump to contributing.

This tutorial is intended for programmers who already know how pointers and references work and are used to systems programming concepts such as integer widths and memory management. We intend to cover, primarily, the differences between Rust and C++ to get you writing Rust programs quickly without lots of fluff you probably already know.

Hopefully, Rust is a pretty intuitive language for C++ programmers. Most of the syntax is pretty similar. The big difference (in my experience) is that the sometimes vague concepts of good systems programming are strictly enforced by the compiler. This can be infuriating at first - there are things you want to do, but the compiler won't let you (at least in safe code), and sometimes these things are safe, but you can't convince the compiler of that. However, you'll quickly develop a good intuition for what is allowed. Communicating your own notions of memory safety to the compiler requires some new and sometimes complicated type annotations. But if you have a strong idea of lifetimes for your objects and experience with generic programming, they shouldn't be too tough to learn.

This tutorial started as a series of blog posts. Partly as an aid for me (@nrc) learning Rust (there is no better way to check that you have learnt something than to try and explain it to somebody else) and partly because I found the existing resources for learning Rust unsatisfactory - they spent too much time on the basics that I already knew and used higher level intuitions to describe concepts that could better be explained to me using lower level intuitions. Since then, the documentation for Rust has got much better, but I still think that existing C++ programmers are an audience who are a natural target for Rust, but are not particularly well catered for.

Contents

  1. Introduction - Hello world!
  2. Control flow
  3. Primitive types and operators
  4. Unique pointers
  5. Borrowed pointers
  6. Rc and raw pointers
  7. Data types
  8. Destructuring pt 1
  9. Destructuring pt 2
  10. Arrays and vecs
  11. Graphs and arena allocation
  12. Closures and first-class functions

Other resources

  • The Rust book/guide - the best place for learning Rust in general and probably the best place to go for a second opinion on stuff here or for stuff not covered.
  • Rust API documentation - detailed documentation for the Rust libraries.
  • The Rust reference manual - a little out of date in places, but thorough; good for looking up details.
  • Discuss forum - general forum for discussion or questions about using and learning Rust.
  • StackOverflow Rust questions - answers to many beginner and advanced questions about Rust, but be careful though - Rust has changed a lot over the years and some of the answers might be very out of date.
  • A Firehose of Rust - a recorded talk introducing C++ programmers to how lifetimes, mutable aliasing, and move semantics work in Rust

Contributing

Yes please!

If you spot a typo or mistake, please submit a PR, don't be shy! Please feel free to file an issue for larger changes or for new chapters you'd like to see. I'd also be happy to see re-organisation of existing work or expanded examples, if you feel the tutorial could be improved in those ways.

If you'd like to contribute a paragraph, section, or chapter please do! If you want ideas for things to cover, see the list of issues, in particular those tagged new material. If you're not sure of something, please get in touch by pinging me here (@nrc) or on irc (nrc, on #rust or #rust-internals).

Style

Obviously, the intended audience is C++ programmers. The tutorial should concentrate on things that will be new to experienced C++ programmers, rather than a general audience (although, I don't assume the audience is familiar with the most recent versions of C++). I'd like to avoid too much basic material and definitely avoid too much overlap with other resources, in particular the Rust guide/book.

Work on edge case use cases (e.g., using a different build system from Cargo, or writing syntax extensions, using unstable APIs) is definitely welcome, as is in-depth work on topics already covered at a high level.

I'd like to avoid recipe-style examples for converting C++ code to Rust code, but small examples of this kind are OK.

Use of different formats (e.g., question and answer/FAQs, or larger worked examples) are welcome.

I don't plan on adding exercises or suggestions for mini-projects, but if you're interested in that, let me know.

I'm aiming for a fairly academic tone, but not too dry. All writing should be in English (British English, not American English; although I would be very happy to have localisations/translations into any language, including American English) and be valid GitHub markdown. For advice on writing style, grammar, punctuation, etc. see the Oxford Style Manual or The Economist Style Guide. Please limit width to 80 columns. I am a fan of the Oxford comma.

Don't feel like work has to be perfect to be submitted, I'm happy to edit and I'm sure other people will be in the future.

Comments
  • Compilation as PDF file

    Compilation as PDF file

    Hello,

    it will be nice to have a PDF version of this document.

    Maybe you should consider using Gitbook https://www.gitbook.com/ (online ... but I wonder if that's not a paid service even for public document) Gitbook can also be used offline (it's a npm tool)

    An other option could be to use pandoc https://pandoc.org/

    What is your opinion?

    Kind regards

    opened by scls19fr 3
  • Update destructuring 2.md

    Update destructuring 2.md

    I'm very new to Rust and the changes I proposed may either be incorrect or not fit in the flow of the document. Please feel free to suggest modifications that I can make or to reject altogether. Thanks.

    opened by SRGOM 3
  • PDF version

    PDF version

    Closes #88

    Renamed some files (avoid blank spaces) Added compile_pdf.sh Bash script to compile Markdown to PDF using pandoc Added compiled PDF file r4cppp.pdf

    opened by scls19fr 2
  • What's cf?

    What's cf?

    At the end of Chapter 5 Borrowing (emphasis mine):

    These have the syntax &'a T (_cf_ &T).

    What's cf? The next sentence makes sense to me, so I guess I'm just being thrown by a contraction or abbreviation that is escaping me?

    P.S. Thank you _so much_ for this! As an experienced C++ programmer, this is exactly the perspective for an intro to Rust I've been looking for.

    opened by U007D 2
  • It is just wrong to say C++ array or other containers do not perform bounds checking.

    It is just wrong to say C++ array or other containers do not perform bounds checking.

    "However, unlike C/C++1, array indexing is bounds checked. In fact all access to arrays is bounds checked, which is another way Rust is a safer language."

    https://github.com/nrc/r4cppp/blob/master/arrays.md#1

    LOL. A safer language. Oh yeah, I got it, another RIIR shit that tries to attack C++ for no reason.

    https://godbolt.org/z/axMxM3v8E

    opened by swang206 1
  • Typo fix in Enum comparison

    Typo fix in Enum comparison

    There was a typo that made reading through this a bit difficult, so I changed the sentence a bit. I also split the sentence at the comma for readability.

    opened by westinn 1
  • added more for() loop examples

    added more for() loop examples

    These additional for() loop examples cover some patterns that other C/C++ programmers might experience. The existing TODO statements give good hints for further reading.

    opened by recombinant 1
  • Added note about mutability going through unique_ptr/Box

    Added note about mutability going through unique_ptr/Box

    I added a note about the fact that mutability does not go "through" std::unique_ptr<T> while it does go through Box<T>. This is a drawback of unique_ptr<T> in C++ but is solved by Rust's ownership rules. I found this important.

    opened by goldsborough 1
  • References to modern C++ features.

    References to modern C++ features.

    I added modern C++ references to several topics because in C++11 and further there are new features that may be associated with Rust features.

    Also I removed int usage from all the pages.

    opened by aserebryakov 1
  • Can you add description of every variable is default immutable?

    Can you add description of every variable is default immutable?

    I feel like default immutable variable is not obvious to me when I first time read this tutorial. For example, I don’t see the reason why use all.iter_mut() in the loop example. Thanks in advance.

    opened by javaThonc 0
  • Attempt to improve wording and reader comprehension

    Attempt to improve wording and reader comprehension

    • Bring the explanation about _ out of the footnote, as it stands out and immediately makes the readers question "why?".
    • Correct the distinction between function parameter and argument.
    • Lead by example by always giving variables and functions meaningful names.
    opened by JohnnyWalkerDesign 0
  • Without the use of y, the code would compile and run successfully.

    Without the use of y, the code would compile and run successfully.

    As of Rust 1.60, the edited examples would compile successfully. This would be irritating for newcomers, as they would expect an error during compilation. Printing the value of the reference y forces the compiler to make an error.

    opened by spekulatiusmensch 0
  • Description of slice is misleading

    Description of slice is misleading

    The chapter about slices https://github.com/nrc/r4cppp/blob/master/arrays.md#slices uses wrong comparisons. It states

    A slice in Rust is just an array whose length is not known at compile time.

    But the rust documentation about slices says https://doc.rust-lang.org/std/slice/

    A dynamically-sized view into a contiguous sequence, [T].

    So a rust slice is similar to a C++ std:span https://en.cppreference.com/w/cpp/container/span and not similar to a rust array (a value) or to an C/C++ array (only a pointer).

    opened by slengfeld 0
  • The captured values are moved when the closure is called, not when it's constructed

    The captured values are moved when the closure is called, not when it's constructed

    WARNING I'm a n00b to Rust, so this is likely incorrect! Please review carefully, and apologies if this is incorrect 😀.

    While closures can capture some environment by moving, it's not entirely clear to me when this happens. I guess it happens when the closure is called, not when the closure is created.

    Hence, I'm proposing to add a few words. I don't think this is made entirely clear elsewhere in the document.

    opened by aaronmcdaid 0
Owner
Nick Cameron
Rust at @microsoft. Formerly @rust-lang core team, @pingcap, @mozilla.
Nick Cameron
Simple autoclicker written in Rust, to learn the Rust language.

RClicker is an autoclicker written in Rust, written to learn more about the Rust programming language. RClicker was was written by me to learn more ab

null 7 Nov 15, 2022
Rust programs written entirely in Rust

mustang Programs written entirely in Rust Mustang is a system for building programs built entirely in Rust, meaning they do not depend on any part of

Dan Gohman 561 Dec 26, 2022
Rust 核心库和标准库的源码级中文翻译,可作为 IDE 工具的智能提示 (Rust core library and standard library translation. can be used as IntelliSense for IDE tools)

Rust 标准库中文版 这是翻译 Rust 库 的地方, 相关源代码来自于 https://github.com/rust-lang/rust。 如果您不会说英语,那么拥有使用中文的文档至关重要,即使您会说英语,使用母语也仍然能让您感到愉快。Rust 标准库是高质量的,不管是新手还是老手,都可以从中

wtklbm 493 Jan 4, 2023
A library for extracting #[no_mangle] pub extern "C" functions (https://docs.rust-embedded.org/book/interoperability/rust-with-c.html#no_mangle)

A library for extracting #[no_mangle] pub extern "C" functions In order to expose a function with C binary interface for interoperability with other p

Dmitrii - Demenev 0 Feb 17, 2022
clone of grep cli written in Rust. From Chapter 12 of the Rust Programming Language book

minigrep is a clone of the grep cli in rust Minigrep will find a query string in a file. To test it out, clone the project and run cargo run body poem

Raunak Singh 1 Dec 14, 2021
Rust-blog - Educational blog posts for Rust beginners

pretzelhammer's Rust blog ?? I write educational content for Rust beginners and Rust advanced beginners. My posts are listed below in reverse chronolo

kirill 5.2k Jan 1, 2023
The ray tracer challenge in rust - Repository to follow my development of "The Raytracer Challenge" book by Jamis Buck in the language Rust

The Ray Tracer Challenge This repository contains all the code written, while step by implementing Ray Tracer, based on the book "The Ray Tracer Chall

Jakob Westhoff 54 Dec 25, 2022
Learn-rust-the-hard-way - "Learn C The Hard Way" by Zed Shaw Converted to Rust

Learn Rust The Hard Way This is an implementation of Zed Shaw's Learn X The Hard Way for the Rust Programming Language. Installing Rust TODO: Instruct

Ryan Levick 309 Dec 8, 2022
Learn to write Rust procedural macros [Rust Latam conference, Montevideo Uruguay, March 2019]

Rust Latam: procedural macros workshop This repo contains a selection of projects designed to learn to write Rust procedural macros — Rust code that g

David Tolnay 2.5k Dec 29, 2022
The Rust Compiler Collection is a collection of compilers for various languages, written with The Rust Programming Language.

rcc The Rust Compiler Collection is a collection of compilers for various languages, written with The Rust Programming Language. Compilers Language Co

null 2 Jan 17, 2022
Integra8 rust integration test framework Rust with a focus on productivity, extensibility, and speed.

integra8 Integra8 rust integration test framework Rust with a focus on productivity, extensibility, and speed. | This repo is in a "work in progress"

exceptional 3 Sep 26, 2022
Neofetch but in Rust (rust-toml-fetch)

rtfetch Configuration Recompile each time you change the config file logo = "arch.logo" # in src/assets. info = [ "", "", "<yellow>{host_n

Paolo Bettelini 6 Jun 6, 2022
Rust Sandbox [code for 15 concepts of Rust language]

Rust-Programming-Tutorial Rust Sandbox [code for 15 concepts of Rust language]. The first time I've been introduced to Rust was on January 2022, you m

Bek Brace 4 Aug 30, 2022
TypeRust - simple Rust playground where you can build or run your Rust code and share it with others

Rust playground Welcome to TypeRust! This is a simple Rust playground where you can build or run your Rust code and share it with others. There are a

Kirill Vasiltsov 28 Dec 12, 2022
Rust Imaging Library: A high-level Rust imaging crate.

ril Rust Imaging Library: A performant and high-level Rust imaging crate. Documentation • Crates.io • Discord What's this? This is a Rust crate design

Jay3332 18 Jan 5, 2023
In this repository you can find modules with code and comments that explain rust syntax and all about Rust lang.

Learn Rust What is this? In this repository you can find modules with code and comments that explain rust syntax and all about Rust lang. This is usef

Domagoj Ratko 5 Nov 5, 2022
Game Boy Emulator written in Rust, as a way to fully grasp the Rust programming language

Flan's Game Boy Emulator Game Boy Emulator written in Rust, as a way to get hands-on with the Rust programming language, and creating a proper project

Flan 3 Dec 31, 2022
Code Examples in Rust. Reviewing RUST

There are some RUST example code here. Run like this cargo run --example enums cargo run --example iterator ... You can learn about RUST coding from

James Johnson 9 Oct 1, 2022
Rust implementation of Andrej Karpathy's micrograd for purposes of learning both ML and Rust.

micrograd_rs Rust implementation of Andrej Karpathy's micrograd for purposes of learning both ML and Rust. Main takeaways Basically the same takeaways

null 3 Oct 28, 2022