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 two editions: 2015 and 2018. 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).

22255 questions
575
votes
11 answers

What are the differences between Rust's `String` and `str`?

Why does Rust have String and str? What are the differences between String and str? When does one use String instead of str and vice versa? Is one of them getting deprecated?
Daniel Fath
  • 11,537
  • 6
  • 39
  • 72
382
votes
5 answers

Why doesn't println! work in Rust unit tests?

I've implemented the following method and unit test: use std::fs::File; use std::path::Path; use std::io::prelude::*; fn read_file(path: &Path) { let mut file = File::open(path).unwrap(); let mut contents = String::new(); …
ruipacheco
  • 11,526
  • 14
  • 63
  • 116
342
votes
1 answer

Why does the Rust compiler not optimize code assuming that two mutable references cannot alias?

As far as I know, reference/pointer aliasing can hinder the compiler's ability to generate optimized code, since they must ensure the generated binary behaves correctly in the case where the two references/pointers indeed alias. For instance, in the…
Zhiyao
  • 3,078
  • 2
  • 7
  • 16
300
votes
12 answers

How do I print the type of a variable in Rust?

I have the following: let mut my_number = 32.90; How do I print the type of my_number? Using type and type_of did not work. Is there another way I can print the number's type?
user2431012
  • 3,109
  • 2
  • 11
  • 7
298
votes
5 answers

How do I concatenate strings?

How do I concatenate the following combinations of types: str and str String and str String and String
jsalter
  • 3,210
  • 2
  • 14
  • 9
296
votes
5 answers

How to disable unused code warnings in Rust?

struct SemanticDirection; fn main() {} warning: struct is never used: `SemanticDirection` --> src/main.rs:1:1 | 1 | struct SemanticDirection; | ^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: #[warn(dead_code)] on by default I will turn these…
Andrew Wagner
  • 17,943
  • 18
  • 70
  • 92
280
votes
2 answers

Why can't I store a value and a reference to that value in the same struct?

I have a value and I want to store that value and a reference to something inside that value in my own type: struct Thing { count: u32, } struct Combined<'a>(Thing, &'a u32); fn make_combined<'a>() -> Combined<'a> { let thing = Thing {…
Shepmaster
  • 274,917
  • 47
  • 731
  • 969
279
votes
6 answers

How to match a String against string literals?

I'm trying to figure out how to match a String in Rust. I initially tried matching like this, but I figured out Rust cannot implicitly cast from std::string::String to &str. fn main() { let stringthing = String::from("c"); match…
Jeroen
  • 11,661
  • 11
  • 46
  • 92
267
votes
4 answers

What is the difference between iter and into_iter?

I am doing the Rust by Example tutorial which has this code snippet: // Vec example let vec1 = vec![1, 2, 3]; let vec2 = vec![4, 5, 6]; // `iter()` for vecs yields `&i32`. Destructure to `i32`. println!("2 in vec1: {}", vec1.iter() .any(|&x| x…
vitiral
  • 6,177
  • 5
  • 22
  • 38
260
votes
7 answers

Convert a String to int?

Note: this question contains deprecated pre-1.0 code! The answer is correct, though. To convert a str to an int in Rust, I can do this: let my_int = from_str::(my_str); The only way I know how to convert a String to an int is to get a slice of…
mmtauqir
  • 6,169
  • 9
  • 30
  • 42
259
votes
4 answers

Rust package with both a library and a binary?

I would like to make a Rust package that contains both a reusable library (where most of the program is implemented), and also an executable that uses it. Assuming I have not confused any semantics in the Rust module system, what should my…
Andrew Wagner
  • 17,943
  • 18
  • 70
  • 92
243
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
  • 7,479
  • 12
  • 48
  • 94
233
votes
3 answers

What are Rust's exact auto-dereferencing rules?

I'm learning/experimenting with Rust, and in all the elegance that I find in this language, there is one peculiarity that baffles me and seems totally out of place. Rust automatically dereferences pointers when making method calls. I made some tests…
kFYatek
  • 4,043
  • 4
  • 18
  • 14
228
votes
10 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
  • 27,785
  • 32
  • 104
  • 177
196
votes
6 answers

Why are Rust executables so huge?

Just having found Rust and having read the first two chapters of the documentation, I find the approach and the way they defined the language particularly interesting. So I decided to get my fingers wet and started out with Hello world... I did so…
BitTickler
  • 8,021
  • 3
  • 26
  • 45
1
2 3
99 100