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
17
votes
2 answers

How do I use integer number literals when using generic types?

I wanted to implement a function computing the number of digits within any generic type of integer. Here is the code I came up with: extern crate num; use num::Integer; fn int_length(mut x: T) -> u8 { if x == 0 { return 1; …
Léo Ercolanelli
  • 1,000
  • 1
  • 8
  • 11
17
votes
3 answers

Why does my string not match when reading user input from stdin?

I'm trying to get user input and check if the user put in "y" or "n". Surprisingly, in the below code, neither the if nor the if else case executes! Apparently, correct_name is neither "y" nor "n". How can that be? Am I doing my string conversion…
Joe
  • 355
  • 3
  • 8
17
votes
2 answers

How to use the Fn traits (closures) in Rust function signatures?

I want to write an i32-returning function that accepts a closure taking zero arguments, a closure taking one argument, and a closure taking two arguments, where all closure arguments are of type i32 and every closure returns f32. What is that…
user
  • 4,920
  • 3
  • 25
  • 38
17
votes
3 answers

Printing a path in Rust

How could I print a path in Rust? I tried the following in order to print the current working directory: use std::os; fn main() { let p = os::getcwd(); println!("{}", p); } But rustc returns with the following error: [wei2912@localhost…
wei2912
  • 6,141
  • 2
  • 19
  • 20
17
votes
1 answer

how to compile and link rust code into an android apk packed application

I'm trying to add Rust code to an android NDK sample (native-activity); Whenever I link Rust code (compiled as a .a) into the .so , it fails to run. I went on information from here to get an android aware rust compiler and 'standalone…
centaurian_slug
  • 3,129
  • 1
  • 17
  • 16
17
votes
2 answers

How to handle long running external function calls such as blocking I/O in Rust?

Editor's note: This question is from a version of Rust prior to 1.0 and uses terms and functions that do not exist in Rust 1.0 code. The concepts expressed are still relevant. I need to read data provided by an external process via a POSIX file…
Zargony
  • 9,615
  • 3
  • 44
  • 44
17
votes
1 answer

Can we create custom Rust operators?

I know we can implement traits that override the standard arithmetic operators. Can we also create our own traits that overload custom operators? I have come to really enjoy Haskell's system for defining operators.
MFlamer
  • 2,340
  • 2
  • 18
  • 25
16
votes
4 answers

error: failed to run custom build command for `ring v0.16.20`

I want to build rust 1.59 project with musl in macOS Monterey 12.3.1 with M1 chip, then I run this command: rustup target add x86_64-unknown-linux-musl cargo build --release --target=x86_64-unknown-linux-musl but the project build output like…
Dolphin
  • 29,069
  • 61
  • 260
  • 539
16
votes
1 answer

rust-openssl: Could not find directory of OpenSSL installation

I am attempting to compile a rust binary in docker but the compilation fails saying openssl is not found despite it being installed. Other answers suggest that having pkg-config and libssl-dev installed resolves the issue, but they already are…
Qwertie
  • 5,784
  • 12
  • 45
  • 89
16
votes
2 answers

How to initialize a vector with values 0 to n?

How do I initialize a vector from 0 to n in Rust? Is there another way of doing that than creating an empty vector and invoking push inside a loop? I prefer a one-liner.
Thorkil Værge
  • 2,727
  • 5
  • 32
  • 48
16
votes
1 answer

Can I define my own "strong" type alias in Rust?

tl;dr in Rust, is there a "strong" type alias (or typing mechanism) such that the rustc compiler will reject (emit an error) for mix-ups that may be the same underlying type? Problem Currently, type aliases of the same underlying type may be…
JamesThomasMoon
  • 6,169
  • 7
  • 37
  • 63
16
votes
1 answer

rust solana build error: no such subcommand: +bpf

I am new to solana and rust, recently i have installed thier example-helloworld from this repo- https://github.com/solana-labs/example-helloworld . Whenever i have tried to build the rust program using npm scripts or going to the rust program…
abhishek
  • 189
  • 1
  • 3
16
votes
1 answer

Is it possible to use Rust's log info for tests?

I have some tests which use info! from Rust's log crate. I tried: RUST_LOG=all cargo test -- --nocapture my_tests but the logs simply won't come out. I didn't init the logger though, because puttin env_logger::init(); won't work: failed to resolve:…
Gatonito
  • 1,662
  • 5
  • 26
  • 55
16
votes
2 answers

Why is the size of a tuple or struct not the sum of the members?

assert_eq!(12, mem::size_of::<(i32, f64)>()); // failed assert_eq!(16, mem::size_of::<(i32, f64)>()); // succeed assert_eq!(16, mem::size_of::<(i32, f64, i32)>()); // succeed Why is it not 12 (4 + 8)? Does Rust have special treatment for tuples?
wangliqiu
  • 369
  • 1
  • 9
16
votes
1 answer

Reborrowing of mutable reference

When I wondered how a mutable reference could move into a method, all the questions began. let a = &mut x; a.somemethod(); // value of a should have moved a.anothermethod(); // but it works. I've googled a lot. (really a lot) And I've noticed that…
kwonryul
  • 481
  • 3
  • 10
1 2 3
99
100