Questions tagged [rust]

Rust is a systems programming language without a garbage collector focused on three goals: safety, speed, and concurrency. Use this tag for questions about code written in Rust. Use an edition specific tag for questions that refer to code which requires a particular edition, like [rust-2018]. Use more specific tags for subtopics like [rust-cargo] and [rust-macros].

Rust is a systems programming language focused on three goals: safety, speed, and concurrency. It maintains these goals without needing a garbage collector, making it a useful language for a number of use cases other languages aren’t good at: embedding in other languages, programs with specific space and time requirements, and writing low-level code, like device drivers and operating systems.

It improves on current languages targeting this space by having a number of compile-time safety checks that produce no runtime overhead, while eliminating all data races. Rust also aims to achieve ‘zero-cost abstractions’ even though some of these abstractions feel like those of a high-level language. Even then, Rust still allows precise control like a low-level language would.

Try Rust online in the Rust Playground

The Rust Playground is an online application that allows you to experiment with Rust by editing and running Rust code from the comfort of your browser; no need to install Rust locally! Several crates (Rust's reusable libraries) are available in the playground to showcase some of Rust's ecosystem.

Version

After a long period of iteration and experimentation, Rust 1.0 shipped on May 15th, 2015. This release is the official beginning of the Rust language's commitment to stability, and as such it offers a firm foundation for building applications and libraries. From this point forward, breaking changes are largely out of scope (some minor caveats apply, such as compiler bugs).

Rust employs three release channels: stable, beta, and nightly. Every six weeks the beta channel is released as a stable version and the current nightly channel becomes the beta candidate.

Edition

Even though Rust commits to stability, editions are used to introduce changes that would be breaking (new keyword for instance). Every version of the compiler supports every edition introduced before its release. You just mark your crate with the edition you want to target and you get the feature of this edition.

Currently, there are three editions: 2015 2018, and 2021. Find out more in the Edition Guide.

What does it do?

Rust supports a mixture of programming styles: imperative procedural, concurrent actor, object-oriented and functional. It supports generic programming and meta-programming, in both static and dynamic styles. Rust is also capable of creating bindings for C foreign function interfaces.

The language design pursues the following goals:

  • Compile-time error detection and prevention.
  • Clarity and precision of expression.
  • Run-time efficiency.
  • High-level zero-cost abstractions.
  • Safe concurrency.

Standard Library

You can view what the standard library has to offer, and search through it, here. The scope of the standard library will continue to grow in future versions of the language.

Getting Started

To get started with the language:

  1. Start with the book.
  2. Open up the standard library documentation.
  3. Read Rust by Example.
  4. When you are ready for the deepest and darkest arts of Rust, dive into The Rustonomicon.

To help your memory, there is a cheat sheet with references to these books.

You can find a lot more learning resources (including non-English ones) in the rust-learning repository or in the rust-unofficial repository.

Getting Help

Not all questions are suitable for Stack Overflow, and discussions certainly are not. If you wish to ask for a recommendation for an IDE, a library, or wish to discuss about the best way to organize a bit of code, then you may consider alternative venues.

More open-ended questions and discussions are welcome on:

There is a list of Rust IRC channels on the community page, and there are even language-specific channels if English is not your forte.

Additionally, the AreWeXYet collection of websites provide helpful summaries and lists of thematic resources:

Producing a Minimal, Reproducible Example (MRE) for Rust code

Questions on Stack Overflow that seek debugging help ("why isn't this code working?") must include the shortest code necessary to reproduce it in the question itself. Without it, the question is off-topic and is likely to be closed. Here are some common points to follow to reduce your code to create a good MRE:

  • Try to run your code in a different environment.

  • If your code fails to compile, include a copy of the error message, preferably complete and unmodified from the compiler's output.

  • Remove unused

    • crates
    • modules
    • types
    • enum variants / members
    • struct members
    • function arguments / return values
  • Combine multiple modules into a single file by rewriting mod foo; as mod foo { /* contents of foo.rs */ }

  • Replace complete or partial statements or entire function bodies with the macro unimplemented!().

  • Replace booleans with hard-coded true or false values

  • Remove containing loops and conditional flow statements.

Remember that some steps might "unlock" other steps; try to apply each step in turn until no steps can be followed! Ensure that your error continues to occur after each change to avoid going down the wrong path.

There's also some information that you should provide about your code:

  • It will be assumed that you are using the current stable version of Rust. If you are not using this version of Rust, state your version. This can be found by running rustc --version.

  • If you are using crates, state the versions of every crate that you are using. This can be found in your Cargo.lock file.

Books

Code Editors & IDEs:

For a comparison of editors' features, see: Text editor features overview (Syntax highlighting, Snippets, Code Completion, Linting, Go-to Definition, Syntax Checking).

38522 questions
323
votes
0 answers

Managing the lifetimes of garbage-collected objects

I am making a simplistic mark-and-compact garbage collector. Without going too much into details, the API it exposes is like this: /// Describes the internal structure of a managed object. pub struct Tag { ... } /// An unmanaged pointer to a…
isekaijin
  • 19,076
  • 18
  • 85
  • 153
312
votes
8 answers

How do I create a global, mutable singleton?

What is the best way to create and use a struct with only one instantiation in the system? Yes, this is necessary, it is the OpenGL subsystem, and making multiple copies of this and passing it around everywhere would add confusion, rather than…
stevenkucera
  • 3,855
  • 2
  • 18
  • 13
295
votes
3 answers

What's the de-facto way of reading and writing files in Rust 1.x?

With Rust being comparatively new, I've seen far too many ways of reading and writing files. Many are extremely messy snippets someone came up with for their blog, and 99% of the examples I've found (even on Stack Overflow) are from unstable builds…
Jared
  • 4,240
  • 4
  • 22
  • 27
293
votes
6 answers

How can I include a module from another file from the same project?

By following this guide I created a Cargo project. src/main.rs fn main() { hello::print_hello(); } mod hello { pub fn print_hello() { println!("Hello, world!"); } } which I run using cargo build && cargo run and it compiles…
ave
  • 18,083
  • 9
  • 30
  • 39
275
votes
11 answers

Why are explicit lifetimes needed in Rust?

I was reading the lifetimes chapter of the Rust book, and I came across this example for a named/explicit lifetime: struct Foo<'a> { x: &'a i32, } fn main() { let x; // -+ x goes into scope …
corazza
  • 31,222
  • 37
  • 115
  • 186
265
votes
3 answers

How can a Rust program access metadata from its Cargo package?

How do you access a Cargo package's metadata (e.g. version) from the Rust code in the package? In my case, I am building a command line tool that I'd like to have a standard --version flag, and I'd like the implementation to read the version of the…
Jimmy
  • 35,686
  • 13
  • 80
  • 98
264
votes
30 answers

Cargo build hangs with " Blocking waiting for file lock on the registry index" after building parity from source

I followed the readme instructions for building Parity from source and then executed: cargo build --release ~/.cargo/bin/cargo build --release as instructed, both of which returned the following message while the prompt hung: Blocking waiting for…
Naruto Sempai
  • 6,233
  • 8
  • 35
  • 51
264
votes
3 answers

What is the equivalent of the join operator over a vector of Strings?

I wasn't able to find the Rust equivalent for the "join" operator over a vector of Strings. I have a Vec and I'd like to join them as a single String: let string_list = vec!["Foo".to_string(),"Bar".to_string()]; let joined =…
Davide Aversa
  • 5,628
  • 6
  • 28
  • 40
260
votes
4 answers

What is this question mark operator about?

I'm reading the documentation for File: //.. let mut file = File::create("foo.txt")?; //.. What is the ? in this line? I do not recall seeing it in the Rust Book before.
Angel Angel
  • 19,670
  • 29
  • 79
  • 105
259
votes
2 answers

Why is there a large performance impact when looping over an array with 240 or more elements?

When running a sum loop over an array in Rust, I noticed a huge performance drop when CAPACITY >= 240. CAPACITY = 239 is about 80 times faster. Is there special compilation optimization Rust is doing for "short" arrays? Compiled with rustc -C…
Guy Korland
  • 9,139
  • 14
  • 59
  • 106
251
votes
6 answers

How do I convert a Vector of bytes (u8) to a string?

I am trying to write simple TCP/IP client in Rust and I need to print out the buffer I got from the server. How do I convert a Vec (or a &[u8]) to a String?
Athabaska Dick
  • 3,855
  • 3
  • 20
  • 22
246
votes
6 answers

What is the difference between Copy and Clone?

This issue seems to imply it's just an implementation detail (memcpy vs ???), but I can't find any explicit description of the differences.
user12341234
  • 6,573
  • 6
  • 23
  • 48
240
votes
9 answers

Default function arguments in Rust

Is it possible to create a function with a default argument? fn add(a: int = 1, b: int = 2) { a + b }
Jeroen
  • 15,257
  • 12
  • 59
  • 102
239
votes
4 answers

Why is it discouraged to accept a reference &String, &Vec, or &Box as a function argument?

I wrote some Rust code that takes a &String as an argument: fn awesome_greeting(name: &String) { println!("Wow, you are awesome, {}!", name); } I've also written code that takes in a reference to a Vec or Box: fn total_price(prices: &Vec)…
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
226
votes
3 answers

How can I build multiple binaries with Cargo?

I'd like to make a project with a daemon and a client, connecting through a unix socket. A client and a daemon requires two binaries, so how do I tell Cargo to build two targets from two different sources? To add a bit of fantasy, I'd like to have…
RallionRl
  • 2,453
  • 2
  • 10
  • 9