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
823 votes
11 answers
141k views

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?
  • 14.7k
515 votes
7 answers
121k 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(); ...
455 votes
9 answers
287k views

How do I concatenate strings?

How do I concatenate the following combinations of types: str and str String and str String and String
  • 4,808
421 votes
9 answers
178k views

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(...
397 votes
4 answers
96k 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`. ...
  • 7,776
389 votes
16 answers
159k 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?
  • 4,007
387 votes
1 answer
49k 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 ...
  • 3,820
386 votes
7 answers
307k 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 ...
  • 7,719
364 votes
7 answers
133k 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() { ...
  • 14k
360 votes
4 answers
50k 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 ...
  • 349k
336 votes
4 answers
107k 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 ...
323 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 ...
  • 18.5k
297 votes
3 answers
45k 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 ...
  • 5,053
295 votes
6 answers
269k 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");
  • 29.8k
294 votes
6 answers
70k views

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 ...
  • 10.3k
278 votes
5 answers
125k 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.
  • 3,219
270 votes
6 answers
128k 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 ...
  • 3,355
262 votes
10 answers
30k 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; ...
  • 30.1k
258 votes
6 answers
175k 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!"); } } ...
  • 16.9k
253 votes
2 answers
22k 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 ...
  • 8,655
249 votes
3 answers
126k 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 (...
  • 3,710
235 votes
3 answers
35k 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 ...
  • 34.4k
233 votes
3 answers
147k 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"....
222 votes
4 answers
65k 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.
  • 17.8k
211 votes
5 answers
179k 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?
211 votes
2 answers
19k views

Why is it discouraged to accept a reference to a String (&String), Vec (&Vec), or Box (&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 ...
  • 349k
205 votes
4 answers
52k 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.
  • 6,103
198 votes
3 answers
21k 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 ...
  • 4,172
196 votes
3 answers
66k 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 ...
  • 2,153
193 votes
7 answers
91k 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 }
  • 14k
189 votes
27 answers
86k 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 ...
189 votes
7 answers
169k 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 ...
  • 8,734
186 votes
1 answer
43k 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 ...
184 votes
2 answers
54k 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 .... ...
  • 4,344
183 votes
2 answers
58k 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 ...
  • 2,052
179 votes
13 answers
53k 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 ...
  • 5,466
172 votes
4 answers
26k 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 ...
  • 20.2k
172 votes
1 answer
92k 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....
  • 2,583
171 votes
2 answers
92k 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 ...
  • 8,734
168 votes
3 answers
22k 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 ...
  • 349k
166 votes
5 answers
86k 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 ...
165 votes
5 answers
82k 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] // ...
  • 4,640
165 votes
2 answers
42k 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 ...
164 votes
5 answers
129k views

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....
  • 5,367
163 votes
4 answers
146k 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).
  • 24.8k
162 votes
4 answers
36k 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(...
  • 25.6k
158 votes
9 answers
70k 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 ...
156 votes
2 answers
36k views

What's the difference between use and extern?

I'm new to Rust. I think that use is used to import identifiers into the current scope and extern is used to declare an external module. But this understanding (maybe wrong) doesn't make any sense to ...
  • 2,161
156 votes
2 answers
24k views

What are the identifiers denoted with a single apostrophe (')?

I've encountered a number of types in Rust denoted with a single apostrophe: 'static 'r 'a What is the significance of that apostrophe (')? Maybe it's a modifier of references (&)? Generic typing ...
  • 2,978
154 votes
4 answers
43k views

Idiomatic callbacks in Rust

In C/C++ I'd normally do callbacks with a plain function pointer, maybe passing a void* userdata parameter too. Something like this: typedef void (*Callback)(); class Processor { public: void ...
  • 82k

1
2 3 4 5
646