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
215
votes
11 answers

How do I fix the Rust error "linker 'cc' not found" for Debian on Windows 10?

I'm running Debian on Windows 10 (Windows Subsystem for Linux) and installed Rust using the command: curl https://sh.rustup.rs -sSf | sh There were no errors in the install, but when I tried to compile with rustc I got the error linker 'cc' not…
Thane Plummer
  • 7,966
  • 3
  • 26
  • 30
215
votes
2 answers

How to use a local unpublished crate?

I've made a library: cargo new my_lib and I want to use that library in a different program: cargo new my_program --bin extern crate my_lib; fn main { println!("Hello, World!"); } what do I need to do to get this to work? They aren't in the…
Andre S.
  • 2,372
  • 2
  • 14
  • 9
214
votes
3 answers

When does a closure implement Fn, FnMut and FnOnce?

What are the specific conditions for a closure to implement the Fn, FnMut and FnOnce traits? That is: When does a closure not implement the FnOnce trait? When does a closure not implement the FnMut trait? When does a closure not implement the Fn…
Denilson Amorim
  • 9,642
  • 6
  • 27
  • 31
209
votes
4 answers

How do I stop iteration and return an error when Iterator::map returns a Result::Err?

I have a function that returns a Result: fn find(id: &Id) -> Result { // ... } Then another using it like this: let parent_items: Vec = parent_ids.iter() .map(|id| find(id).unwrap()) .collect(); How do I handle…
Kai Sellgren
  • 27,954
  • 10
  • 75
  • 87
207
votes
2 answers

What is the correct way to return an Iterator (or any other trait)?

The following Rust code compiles and runs without any issues. fn main() { let text = "abc"; println!("{}", text.split(' ').take(2).count()); } After that, I tried something like this .... but it didn't compile fn main() { let text =…
forgemo
  • 4,634
  • 5
  • 22
  • 25
206
votes
3 answers

What is the difference between traits in Rust and typeclasses in Haskell?

Traits in Rust seem at least superficially similar to typeclasses in Haskell, however I've seen people write that there are some differences between them. I was wondering exactly what these differences are.
LogicChains
  • 4,332
  • 2
  • 18
  • 27
206
votes
8 answers

Is it possible to use global variables in Rust?

I know that in general, global-variables are to be avoided. Nevertheless, I think in a practical sense, it is sometimes desirable (in situations where the variable is integral to the program) to use them. In order to learn Rust, I'm currently…
Brian Oh
  • 9,604
  • 12
  • 49
  • 68
203
votes
5 answers

How do I iterate over a range with a custom step?

How can I iterate over a range in Rust with a step other than 1? I'm coming from a C++ background so I'd like to do something like for(auto i = 0; i <= n; i+=2) { //... } In Rust I need to use the range function, and it doesn't seem like there…
Syntactic Fructose
  • 18,936
  • 23
  • 91
  • 177
201
votes
2 answers

Is there a faster/shorter way to initialize variables in a Rust struct?

In the following example, I would much prefer to assign a value to each field in the struct in the declaration of the fields. Alternatively, it effectively takes one additional statement for each field to assign a value to the fields. All I want to…
Brian Oh
  • 9,604
  • 12
  • 49
  • 68
199
votes
6 answers

What is the best way to concatenate vectors in Rust?

Is it even possible to concatenate vectors in Rust? If so, is there an elegant way to do so? I have something like this: let mut a = vec![1, 2, 3]; let b = vec![4, 5, 6]; for val in &b { a.push(val); } Does anyone know of a better way?
Joe Thomas
  • 5,807
  • 6
  • 25
  • 36
195
votes
2 answers

Cannot move out of borrowed content / cannot move out of behind a shared reference

I don't understand the error cannot move out of borrowed content. I have received it many times and I have always solved it, but I've never understood why. For example: for line in self.xslg_file.iter() { self.buffer.clear(); for…
Peekmo
  • 2,843
  • 2
  • 19
  • 25
193
votes
3 answers

When is it appropriate to use an associated type versus a generic type?

In this question, an issue arose that could be solved by changing an attempt at using a generic type parameter into an associated type. That prompted the question "Why is an associated type more appropriate here?", which made me want to know…
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
191
votes
4 answers

How to convert a String into a &'static str

How do I convert a String into a &str? More specifically, I would like to convert it into a str with the static lifetime (&'static str).
Christoph
  • 26,519
  • 28
  • 95
  • 133
191
votes
13 answers

How can I access command line parameters in Rust?

The Rust tutorial does not explain how to take parameters from the command line. fn main() is only shown with an empty parameter list in all examples. What is the correct way of accessing command line parameters from main?
shutefan
  • 6,156
  • 8
  • 23
  • 23
188
votes
5 answers

How do I use a macro across module files?

I have two modules in separate files within the same crate, where the crate has macro_rules enabled. I want to use the macros defined in one module in another module. // macros.rs #[macro_export] // or not? is ineffectual for this,…
user
  • 4,920
  • 3
  • 25
  • 38