Skip to main content

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].

Filter by
Sorted by
Tagged with
1030 votes
16 answers
214k views

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

Why does Rust have both String and str? What are the differences between them, and when should one be used over the other? Is one of them getting deprecated?
Daniel Fath's user avatar
  • 17.6k
634 votes
9 answers
196k views

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(); ...
ruipacheco's user avatar
594 votes
9 answers
497k views

How do I concatenate strings?

How do I concatenate the following combinations of types: str and str String and str String and String
jsalter's user avatar
  • 6,198
528 votes
14 answers
277k views

How do you disable dead code warnings at the crate level in Rust?

While tinkering in Rust, I repeatedly encountered a lot of dead code warnings that made it difficult to focus. I tried using the outer attribute #[allow(dead_code)], but it only silences one warning ...
Andrew Wagner's user avatar
499 votes
9 answers
498k views

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::<int>(my_str); The only way I ...
mmtauqir's user avatar
  • 9,089
490 votes
6 answers
151k views

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`. ...
vitiral's user avatar
  • 8,910
475 votes
18 answers
229k views

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

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's user avatar
  • 4,867
435 votes
4 answers
64k views

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 ...
Shepmaster's user avatar
  • 419k
432 votes
10 answers
198k views

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() { ...
Jeroen's user avatar
  • 16.3k
416 votes
1 answer
53k views

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 ...
Zhiyao's user avatar
  • 4,324
410 votes
4 answers
156k views

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 ...
Andrew Wagner's user avatar
382 votes
5 answers
211k views

What is the syntax for a multiline string literal?

I'm having a hard time figuring out how string syntax works in Rust. Specifically, I'm trying to figure out how to make a multiple line string.
Dumbapples's user avatar
  • 4,419
378 votes
7 answers
425k views

How do I split a string in Rust?

From the documentation, it's not clear. In Java you could use the split method like so: "some string 123 ffd".split("123");
Incerteza's user avatar
  • 33.9k
368 votes
7 answers
106k views

Why are Rust executables so huge?

I find the approach and the way they define the language in the first two chapters of the documentation particularly interesting. So I decided to get my fingers wet and started out with "Hello, ...
BitTickler's user avatar
  • 11.6k
352 votes
9 answers
196k views

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 ...
stevenkucera's user avatar
  • 4,311
346 votes
4 answers
58k views

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 ...
kFYatek's user avatar
  • 5,803
326 votes
3 answers
196k views

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 (...
Jared's user avatar
  • 4,600
325 votes
0 answers
9k views

Managing the lifetimes of garbage-collected objects [closed]

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 ...
isekaijin's user avatar
  • 19.6k
320 votes
6 answers
269k views

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!"); } } ...
ave's user avatar
  • 19k
288 votes
4 answers
108k views

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's user avatar
287 votes
24 answers
160k views

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 ...
Naruto Sempai's user avatar
287 votes
3 answers
226k views

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<String> and I'd like to join them as a single String: let string_list = vec!["Foo"....
Davide Aversa's user avatar
285 votes
6 answers
286k views

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<u8> (or a &[u8]) to a String?
Athabaska Dick's user avatar
284 votes
5 answers
59k views

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 ...
Jimmy's user avatar
  • 36.6k
281 votes
11 answers
35k views

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; ...
corazza's user avatar
  • 32k
278 votes
6 answers
92k views

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's user avatar
  • 7,023
268 votes
11 answers
167k views

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 ...
Thane Plummer's user avatar
267 votes
10 answers
156k views

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's user avatar
  • 16.3k
260 votes
3 answers
114k views

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 ...
RallionRl's user avatar
  • 2,793
259 votes
2 answers
23k views

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 ...
Guy Korland's user avatar
  • 9,408
258 votes
4 answers
27k views

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 ...
Shepmaster's user avatar
  • 419k
250 votes
5 answers
186k views

Is there a command to update Cargo to the latest official release?

I seem to have diverging versions of rustc and cargo (I think), $ rustc -V rustc 1.9.0 (e4e8b6668 2016-05-18) $ cargo -V cargo 0.10.0-nightly (10ddd7d 2016-04-08) Is there a command akin to pip ...
Filip Allberg's user avatar
244 votes
2 answers
97k views

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 ...
Andre S.'s user avatar
  • 2,652
233 votes
5 answers
69k views

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<Item, ItemError> { // ... } Then another using it like this: let parent_items: Vec<Item> = parent_ids.iter(...
Kai Sellgren's user avatar
  • 29.6k
233 votes
3 answers
69k views

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 ...
Denilson Amorim's user avatar
227 votes
6 answers
206k views

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....
Joe Thomas's user avatar
  • 6,167
223 votes
8 answers
229k views

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 ...
Brian Oh's user avatar
  • 10.4k
221 votes
2 answers
78k views

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 .... ...
forgemo's user avatar
  • 4,774
219 votes
2 answers
154k views

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 ...
Brian Oh's user avatar
  • 10.4k
219 votes
5 answers
140k views

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 ...
Syntactic Fructose's user avatar
218 votes
5 answers
127k views

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] // ...
user's user avatar
  • 5,290
211 votes
3 answers
32k views

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 ...
Shepmaster's user avatar
  • 419k
211 votes
3 answers
26k views

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 ...
LogicChains's user avatar
  • 4,382
206 votes
13 answers
74k views

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 ...
shutefan's user avatar
  • 6,736
205 votes
2 answers
52k views

What's the difference between use and extern crate?

I think that use is used to import identifiers into the current scope and extern crate is used to declare an external module. But this understanding (maybe wrong) doesn't make any sense to me. Can ...
maralla's user avatar
  • 2,671
199 votes
2 answers
112k views

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....
Peekmo's user avatar
  • 2,893
198 votes
4 answers
200k views

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's user avatar
  • 27.4k
198 votes
3 answers
72k views

How to lookup from and insert into a HashMap efficiently?

I'd like to do the following: Lookup a Vec for a certain key, and store it for later use. If it doesn't exist, create an empty Vec for the key, but still keep it in the variable. How to do this ...
Yusuke Shinyama's user avatar
193 votes
4 answers
36k views

How does Rust's 128-bit integer `i128` work on a 64-bit system?

Rust has 128-bit integers, these are denoted with the data type i128 (and u128 for unsigned ints): let a: i128 = 170141183460469231731687303715884105727; How does Rust make these i128 values work on ...
ruohola's user avatar
  • 23.3k
187 votes
1 answer
203k views

How do I convert between numeric types safely and idiomatically?

Editor's note: This question is from a version of Rust prior to 1.0 and references some items that are not present in Rust 1.0. The answers still contain valuable information. What's the idiomatic ...
Caspar's user avatar
  • 7,559

1
2 3 4 5
838