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
409 votes
4 answers
58k 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
  • 391k
244 votes
4 answers
24k 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
  • 391k
125 votes
5 answers
82k views

Is there any way to return a reference to a variable created in a function?

I want to write a program that will write a file in 2 steps. It is likely that the file may not exist before the program is run. The filename is fixed. The problem is that OpenOptions.new().write() ...
Nex's user avatar
  • 1,433
316 votes
8 answers
164k 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
  • 3,895
332 votes
4 answers
53k 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,553
149 votes
1 answer
23k views

What are non-lexical lifetimes?

Rust has an RFC related to non-lexical lifetimes which has been approved to be implemented in the language for a long time. Recently, Rust's support of this feature has improved a lot and is ...
Stargateur's user avatar
  • 24.6k
63 votes
1 answer
16k views

How can I pass a reference to a stack variable to a thread?

I'm writing a WebSocket server where a web client connects to play chess against a multithreaded computer AI. The WebSocket server wants to pass a Logger object into the AI code. The Logger object is ...
Ned Ruggeri's user avatar
  • 1,058
87 votes
7 answers
28k views

Return local String as a slice (&str)

There are several questions that seem to be about the same problem I'm having. For example see here and here. Basically I'm trying to build a String in a local function, but then return it as a &...
anderspitman's user avatar
  • 9,300
968 votes
15 answers
184k 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
  • 16.6k
81 votes
3 answers
28k views

How do I implement a trait I don't own for a type I don't own?

I wanted to implement the Shl trait for Vec, the code is below. This would make things like vec << 4 possible, which would be nice sugar for vec.push(4). use std::ops::Shl; impl<T> Shl&...
le_me's user avatar
  • 3,109
17 votes
3 answers
4k views

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". ...
Joe's user avatar
  • 355
207 votes
2 answers
66k 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,634
36 votes
1 answer
7k views

Returning a reference from a HashMap or Vec causes a borrow to last beyond the scope it's in?

I've got a persistent compile error where Rust complains that I have an immutable borrow while I'm trying to mutably borrow, but the immutable borrow is from another scope, and I'm not bringing ...
Bill Fraser's user avatar
48 votes
1 answer
5k views

Why can I return a reference to a local literal but not a variable?

Why does this code compile? fn get_iter() -> impl Iterator<Item = i32> { [1, 2, 3].iter().map(|&i| i) } fn main() { let _it = get_iter(); } [1, 2, 3] is a local variable and ...
Boiethios's user avatar
  • 38.7k
453 votes
5 answers
127k 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,446
65 votes
8 answers
18k views

How to get mutable references to two array elements at the same time?

fn change(a: &mut i32, b: &mut i32) { let c = *a; *a = *b; *b = c; } fn main() { let mut v = vec![1, 2, 3]; change(&mut v[0], &mut v[1]); } When I compile the ...
user2925565's user avatar
  • 1,302
187 votes
2 answers
58k 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
33 votes
1 answer
9k views

How do I create a heterogeneous collection of objects?

I want to use trait objects in a Vec. In C++ I could make a base class Thing from which is derived Monster1 and Monster2. I could then create a std::vector<Thing*>. Thing objects must store some ...
stevenkucera's user avatar
  • 3,895
80 votes
5 answers
20k views

Why doesn't Rust support trait object upcasting?

Given this code: trait Base { fn a(&self); fn b(&self); fn c(&self); fn d(&self); } trait Derived : Base { fn e(&self); fn f(&self); fn g(&...
kFYatek's user avatar
  • 5,553
136 votes
4 answers
21k views

What's the difference between placing "mut" before a variable name and after the ":"?

Here are two function signatures I saw in the Rust documentation: fn modify_foo(mut foo: Box<i32>) { *foo += 1; *foo } fn modify_foo(foo: &mut i32) { *foo += 1; *foo } Why the different ...
Jimmy Lu's user avatar
  • 4,820
48 votes
4 answers
25k views

How do I write an iterator that returns references to itself?

I am having trouble expressing the lifetime of the return value of an Iterator implementation. How can I compile this code without changing the return value of the iterator? I'd like it to return a ...
elszben's user avatar
  • 495
35 votes
3 answers
5k views

Why is it legal to borrow a temporary?

Coming from C++, I'm rather surprised that this code is valid in Rust: let x = &mut String::new(); x.push_str("Hello!"); In C++, you can't take the address of a temporary, and a temporary won't ...
Sven Marnach's user avatar
109 votes
2 answers
37k views

How to get a reference to a concrete type from a trait object?

How do I get Box<B> or &B or &Box<B> from the a variable in this code: trait A {} struct B; impl A for B {} fn main() { let mut a: Box<dyn A> = Box::new(B); let b =...
Aleksandr's user avatar
  • 1,765
28 votes
1 answer
8k views

"Expected type parameter" error in the constructor of a generic struct

I am trying to store piston textures in a struct. struct TextureFactory<R> where R: gfx::Resources { block_textures: Vec<Rc<Texture<R>>>, } impl<R> TextureFactory&...
Xavier Shay's user avatar
  • 4,067
34 votes
1 answer
14k views

Why is a trait not implemented for a type that clearly has it implemented?

I'm trying to use Diesel to query a MySQL database and display the results with a Handlebars template with Rocket. I have this in models.rs #[derive(Queryable, Serialize)] pub struct Post { pub ...
haheute's user avatar
  • 2,129
54 votes
2 answers
11k views

How can I swap in a new value for a field in a mutable reference to a structure?

I have a struct with a field: struct A { field: SomeType, } Given a &mut A, how can I move the value of field and swap in a new value? fn foo(a: &mut A) { let mut my_local_var = a....
arcyqwerty's user avatar
  • 10.3k
449 votes
18 answers
199k 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,607
68 votes
2 answers
22k views

The compiler suggests I add a 'static lifetime because the parameter type may not live long enough, but I don't think that's what I want

I'm trying to implement something that looks like this minimal example: trait Bar<T> {} struct Foo<T> { data: Vec<Box<Bar<T>>>, } impl<T> Foo<T> { ...
Robert Mason's user avatar
  • 3,949
66 votes
4 answers
25k views

Why do try!() and ? not compile when used in a function that doesn't return Option or Result?

Why does this code not compile? use std::{fs, path::Path}; fn main() { let dir = Path::new("../FileSystem"); if !dir.is_dir() { println!("Is not a directory"); return; } ...
Mathieu David's user avatar
107 votes
1 answer
11k views

How does "for<>" syntax differ from a regular lifetime bound?

Consider the following code: trait Trait<T> {} fn foo<'a>(_b: Box<dyn Trait<&'a usize>>) {} fn bar(_b: Box<dyn for<'a> Trait<&'a usize>>) {} Both ...
George Hilliard's user avatar
27 votes
4 answers
5k views

Cannot obtain a mutable reference when iterating a recursive structure: cannot borrow as mutable more than once at a time

I'm trying to navigate a recursive data structure iteratively in order to insert elements at a certain position. To my limited understanding, this means taking a mutable reference to the root of the ...
Fabian Knorr's user avatar
  • 3,134
276 votes
11 answers
33k 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
  • 31.3k
56 votes
5 answers
13k views

How do I return a reference to something inside a RefCell without breaking encapsulation?

I have a struct that has inner mutability. use std::cell::RefCell; struct MutableInterior { hide_me: i32, vec: Vec<i32>, } struct Foo { //although not used in this particular ...
Drew's user avatar
  • 8,705
195 votes
2 answers
103k 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,843
60 votes
2 answers
19k views

Is it possible to control the size of an array using the type parameter of a generic?

What follows is just used as an example, and not valid Rust code. struct Vec<T: Sized, Count> { a: [T; Count] } Something like it is possible in C++ templates, but I haven't seen it in ...
Byron's user avatar
  • 3,938
45 votes
1 answer
7k views

How can I create my own data structure with an iterator that returns mutable references?

I have created a data structure in Rust and I want to create iterators for it. Immutable iterators are easy enough. I currently have this, and it works fine: // This is a mock of the "real" ...
Mike Pedersen's user avatar
28 votes
1 answer
8k views

Why is this match pattern unreachable when using non-literal patterns?

The following code (playground) let max_column = 7; edge = match current_column { 0 => Edge::Left, max_column => Edge::Right, _ => Edge::NotAnEdge }; results in the following ...
Mike Vella's user avatar
  • 10.2k
23 votes
2 answers
17k views

Cannot move out of value which is behind a shared reference when unwrapping

This is the code I am trying to execute: fn my_fn(arg1: &Option<Box<i32>>) -> i32 { if arg1.is_none() { return 0; } let integer = arg1.unwrap(); *integer } ...
Moebius's user avatar
  • 6,262
40 votes
4 answers
24k views

How can you make a safe static singleton in Rust?

This is something of a controversial topic, so let me start by explaining my use case, and then talk about the actual problem. I find that for a bunch of unsafe things, it's important to make sure ...
Doug's user avatar
  • 33k
72 votes
3 answers
25k views

How to clone a struct storing a boxed trait object?

I wrote a program that has the trait Animal and the struct Dog implementing the trait. It also has a struct AnimalHouse storing an animal as a trait object Box<Animal>. trait Animal { fn ...
Denis Kreshikhin's user avatar
294 votes
6 answers
225k 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
  • 18.1k
34 votes
4 answers
8k views

Conditionally iterate over one of several possible iterators

I'm trying to switch behavior based on an Option input to a function. The idea is to iterate based on whether or not a given Option is present. Here's a minimal, if silly, example: use std::iter; fn ...
Linear's user avatar
  • 21.2k
26 votes
2 answers
4k views

How to fix lifetime error when function returns a serde Deserialize type?

I'm using serde and serde_json 1.0 to decode data from a base64 string: fn from_base64_str<T: Deserialize>(string: &str) -> T { let slice = decode_config(string, URL_SAFE).unwrap(); ...
realli's user avatar
  • 990
65 votes
2 answers
26k views

How do I import from a sibling module?

In src/lib.rs I have the following extern crate opal_core; mod functions; mod context; mod shader; Then in src/context.rs I have something like this, which tries to import symbols from src/shader.rs:...
neon64's user avatar
  • 1,486
61 votes
3 answers
35k views

How do I synchronously return a value calculated in an asynchronous Future?

I am trying to use hyper to grab the content of an HTML page and would like to synchronously return the output of a future. I realized I could have picked a better example since synchronous HTTP ...
Boris's user avatar
  • 1,011
56 votes
3 answers
8k views

Should trait bounds be duplicated in struct and impl?

The following code uses a struct with generic type. While its implementation is only valid for the given trait bound, the struct can be defined with or without the same bound. The struct's fields are ...
user2011659's user avatar
37 votes
2 answers
10k views

How is there a conflicting implementation of `From` when using a generic type?

I'm trying to implement an error enum which can contain an error associated with one of our traits like this: trait Storage { type Error; } enum MyError<S: Storage> { StorageProblem(S::...
Fraser's user avatar
  • 74.8k
36 votes
1 answer
4k views

Do mutable references have move semantics?

fn main() { let mut name = String::from("Charlie"); let x = &mut name; let y = x; // x has been moved say_hello(y); say_hello(y); // but y has not been ...
oberblastmeister's user avatar
34 votes
2 answers
6k views

How do I require a generic type implement an operation like Add, Sub, Mul, or Div in a generic function?

I'm trying to implement a generic function in Rust where the only requirement for the argument is that the multiplication operation should be defined. I'm trying to implement a generic "power", but ...
Maxim Sloyko's user avatar
  • 15.2k
61 votes
1 answer
16k views

Why do I need to import a trait to use the methods it defines for a type?

I have a very simple example of Rust code which fails to compile: extern crate rustc_serialize; use rustc_serialize::base64; fn main() { let auth = format!("{}:{}", "user", "password"); let ...
mhristache's user avatar
  • 2,038

1
2 3 4 5
110