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].
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 ...
asked Aug 30 '15 at 19:06
Shepmaster
269k4646 gold badges710710 silver badges949949 bronze badges
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() ...
asked Sep 20 '15 at 18:34
Nex
90311 gold badge66 silver badges66 bronze badges
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 ...
asked Oct 12 '16 at 18:50
Shepmaster
269k4646 gold badges710710 silver badges949949 bronze badges
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 ...
asked Jan 6 '15 at 3:11
stevenkucera
2,28522 gold badges1515 silver badges1313 bronze badges
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 &...
asked Apr 3 '15 at 7:42
anderspitman
6,06655 gold badges3333 silver badges4747 bronze badges
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 ...
asked Sep 23 '15 at 23:00
Ned Ruggeri
82611 gold badge77 silver badges1313 bronze badges
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 ...
asked May 9 '18 at 10:45
Stargateur
16.9k77 gold badges4242 silver badges6767 bronze badges
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 ...
asked Feb 14 '15 at 20:31
kFYatek
3,93344 gold badges1818 silver badges1414 bronze badges
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 .... ...
asked Dec 17 '14 at 21:39
forgemo
3,79455 gold badges1919 silver badges2525 bronze badges
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&...
asked Aug 20 '14 at 19:45
le_me
2,18922 gold badges2121 silver badges2525 bronze badges
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?
asked Jun 11 '14 at 8:29
Daniel Fath
11.4k66 gold badges3939 silver badges7171 bronze badges
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 ...
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 ...
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 ...
asked May 15 '18 at 7:59
Boiethios
25.1k77 gold badges9090 silver badges134134 bronze badges
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&...
asked Sep 13 '15 at 15:17
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(&...
asked Feb 20 '15 at 15:49
kFYatek
3,93344 gold badges1818 silver badges1414 bronze badges
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....
asked Nov 24 '14 at 5:58
arcyqwerty
8,84322 gold badges3939 silver badges7676 bronze badges
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 ...
asked Jun 8 '17 at 13:30
haheute
1,90922 gold badges2626 silver badges4747 bronze badges
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 ...
asked Jun 23 '16 at 8:50
Fabian Knorr
2,86622 gold badges1414 silver badges2929 bronze badges
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;
}
...
asked May 31 '15 at 8:42
Mathieu David
3,30833 gold badges1414 silver badges2626 bronze badges
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 ...
asked Dec 1 '14 at 4:01
Doug
25.9k2525 gold badges137137 silver badges195195 bronze badges
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 ...
asked Jan 15 '15 at 5:03
stevenkucera
2,28522 gold badges1515 silver badges1313 bronze badges
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> {
...
asked Oct 14 '16 at 23:51
Robert Mason
3,62933 gold badges2828 silver badges4141 bronze badges
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?
asked Feb 13 '14 at 6:49
user2431012
2,97922 gold badges1010 silver badges77 bronze badges
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 ...
asked Feb 18 '15 at 15:46
Jimmy Lu
3,97055 gold badges2222 silver badges2929 bronze badges
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". ...
asked Jan 5 '15 at 4:12
Joe
18511 silver badge88 bronze badges
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....
asked Jan 26 '15 at 21:04
Peekmo
2,21322 gold badges1414 silver badges2323 bronze badges
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 ...
asked May 24 '15 at 9:54
elszben
37511 gold badge33 silver badges66 bronze badges
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
}
...
asked Sep 1 '15 at 18:33
Moebius
4,86344 gold badges3333 silver badges4848 bronze badges
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 ...
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 =...
asked Nov 13 '15 at 7:03
Aleksandr
1,06522 gold badges99 silver badges88 bronze badges
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`.
...
asked Jan 12 '16 at 0:48
vitiral
6,04555 gold badges2222 silver badges3838 bronze badges
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 ...
asked Mar 21 '15 at 15:18
Maxim Sloyko
13k77 gold badges3636 silver badges4747 bronze badges
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 ...
asked Sep 26 '18 at 15:21
Boris
65111 gold badge66 silver badges1414 bronze badges
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; ...
asked Jul 24 '15 at 11:15
corazza
27.5k3232 gold badges104104 silver badges177177 bronze badges
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!");
}
}
which I run ...
asked Oct 15 '14 at 17:47
ave
13.7k77 gold badges2424 silver badges3636 bronze badges
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 ...
asked Jan 25 '15 at 13:07
Byron
3,18311 gold badge2121 silver badges3232 bronze badges
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 ...
asked May 6 '15 at 10:09
user2925565
78022 gold badges77 silver badges1212 bronze badges
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 ...
asked Apr 1 '15 at 22:02
Drew
7,58755 gold badges3838 silver badges4040 bronze badges
I'm using Serde to deserialize an XML file which has the hex value 0x400 as a string and I need to convert it to the value 1024 as a u32.
Do I need to implement the Visitor trait so that I separate ...
asked Oct 15 '17 at 10:15
phodina
96166 silver badges2222 bronze badges
I wrote the following code:
use std::io::{IoResult, Writer};
use std::io::stdio;
fn main() {
let h = |&: w: &mut Writer| -> IoResult<()> {
writeln!(w, "foo")
};
...
asked Jan 20 '15 at 11:27
k-ui
55711 gold badge44 silver badges1010 bronze badges
The architecture of my networking application can be stripped down to the following:
use std::collections::HashMap;
/// Represents remote user. Usually has fields,
/// but we omit them for the sake ...
asked Jul 13 '19 at 9:12
kreo
1,57511 gold badge1212 silver badges2222 bronze badges
I am trying to implement a scenegraph-like data structure in Rust. I would like an equivalent to this C++ code expressed in safe Rust:
struct Node
{
Node* parent; // should be mutable, and ...
asked Mar 22 '16 at 23:32
nulleight
59644 silver badges1111 bronze badges
I have recently seen code using the dyn keyword:
fn foo(arg: &dyn Display) {}
fn bar() -> Box<dyn Display> {}
What does this syntax mean?
asked Jun 1 '18 at 19:39
Shepmaster
269k4646 gold badges710710 silver badges949949 bronze badges
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::...
asked May 20 '16 at 12:54
Fraser
65.3k1414 gold badges213213 silver badges203203 bronze badges
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 ...
asked Dec 5 '17 at 20:36
Sven Marnach
478k106106 gold badges855855 silver badges774774 bronze badges
This code (playground):
#[derive(Clone)]
struct Foo<'a, T: 'a> {
t: &'a T,
}
fn bar<'a, T>(foo: Foo<'a, T>) {
foo.clone();
}
... does not compile:
error[E0599]: no ...
I have an array of an unknown size, and I would like to get a slice of that array and convert it to a statically sized array:
fn pop(barry: &[u8]) -> [u8; 3] {
barry[0..3] // expected array ...
asked Aug 21 '14 at 14:25
Jeroen
11.5k1111 gold badges4444 silver badges9292 bronze badges
A few days ago, there was a question where someone had a problem with linked lifetimes of a mutable reference to a type which contained borrowed data itself. The problem was supplying a reference to ...
asked Aug 23 '15 at 11:02
jtepe
2,92222 gold badges1616 silver badges2929 bronze badges
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 ...
asked Aug 17 '15 at 20:44
Shepmaster
269k4646 gold badges710710 silver badges949949 bronze badges