Newest 'rust' Questions - Stack Overflow

Questions tagged [rust]

Rust is a language designed for writing highly reliable and fast software in a simple way. It can be used from high-level code down to hardware-specific code, and from big irons to tiny devices.

0
votes
1answer
13 views

How do I make these lifetimes match?

Say we have some code like this: struct X { y: String, } trait Foo { fn bar(&mut self, x: &X); } type Stack<'a> = Vec<&'a X>; struct Quux<'a> { stack: ...
0
votes
1answer
31 views

How do I tell Rust that something implements a trait? [duplicate]

I'm trying to write a generic function that returns an iterator. fn one_to_ten<T: Add>() -> std::iter::Iterator<Item = T> { (1..5).chain(5..=10) } It's generic because it needs to ...
0
votes
0answers
14 views

implement one trait for multiple Borrow<T> types causes conflicting implementations

use std::borrow::Borrow; trait Foo { fn bar(); } struct S{} impl <B:Borrow<S>> Foo for B{ fn bar(){ print!("bar"); } } struct D{} impl <B:Borrow<D>> ...
0
votes
1answer
20 views

Including a file from another that is not main.rs nor lib.rs

(I'm a Rust beginner) I have three files : main.rs, board.rs and case.rs. I want to include case.rs into board.rs, and board.rs into main.rs, so the board uses the case, and we can access the board in ...
3
votes
1answer
33 views

Why proc-macros have to be defined in proc-macro crate?

I was trying to create derive macro for my trait, to simplify some stuff. I've encountered some problems: the `#[proc_macro_derive]` attribute is only usable with crates of the `proc-macro` crate ...
0
votes
2answers
29 views

Explanation on References and Borrowing from The Rust book

I'm reading the Rust book and References and Borrowing in Chapter 4 seems to be inconsistent to me. In Reference and Borrowing, figure 4-5 below shows that s points to s1 instead of the actual data on ...
0
votes
1answer
32 views

How to run Rust tests with an explicit time zone (using chrono)

I am building some tests that do timestamp conversions in Rust using the chrono crate, and need to make sure they take into account the local time zone. However, the tests will be run in multiple time ...
0
votes
0answers
26 views

How does mesh coordinates and draw coordinates relate to each other in ggez library?

for example when creating a line, list of points is passed. but graphics::draw also expects xy coordinates let (origin, dest) = (Point::new(0.0, 0.0), Point::new(0.0, 0.0)); let line = graphics::Mesh:...
1
vote
1answer
30 views

Do I need to use some kind of interior mutability to create a cycle between two Arcs?

I have a tree and I want each node of the tree to have a pointer to its parent. struct DataDeclaration { parent: Option<Arc<DataDeclaration>>, children: Option<Vec<Weak<...
1
vote
0answers
39 views

How do I deserialize a struct through its own `new` constructor? [duplicate]

I wish to deserialize the below struct, but using the new constructor to validate the deserialized fields: #[derive(Deserialize)] pub struct Timestamp { values: Vec<u32>, } impl Timestamp {...
0
votes
0answers
19 views

“borrowed value does not live long enough” while splitting strings read from a file and storing them in a graph [duplicate]

I'm trying to read a text file which contains the data of a graph where the vertices are labelled with a string. The format of each line of the file is vertexLabel1 vertexLabel2. I'm using safe-graph ...
1
vote
1answer
33 views

The size for values of type `T` cannot be known at compilation time when using mem::size_of::<T> as an array length

Consider the following function: fn make_array<T>() where T: Sized, { let bytes = [0u8; std::mem::size_of::<T>()]; } For whatever reason it fails to compile error[E0277]: the ...
1
vote
1answer
39 views

Should I implement AddAssign on a newtype?

I've got a newtype: struct NanoSecond(u64); I want to implement addition for this. (I'm actually using derive_more, but here's an MCVE.) impl Add for NanoSecond { fn add(self, other: Self) ->...
1
vote
0answers
46 views

How to expand subpatterns in recursive macro_rules?

I am writing a macro to conveniently match nested structure in an enum type. The idea is to leverage Rust's pattern matching to enforce constant values in certain locations of the structure, or bind ...
-1
votes
1answer
55 views

How do I switch two sections of a vector without conflicting borrows?

I'm going to switch elements in a Vec, but my solution has ownership problem, Is my code totally wrong? Given [1, 2, 3, 4, 5, 6], the expected output is [4, 5, 6, 1, 2, 3]. fn switch(nums: &mut ...
2
votes
1answer
37 views

What order is `on_initialize` invoked across different modules in a Substrate runtime?

I need to be sure that the on_initialize handler for a specific module runs before the same handler before all other modules in my runtime. a) How do ensure this? b) Is there some compile or runtime ...
3
votes
0answers
65 views

Why does FlatBufferBuilder have a lifetime?

Why does FlatBufferBuilder from the Rust flatbuffer library have a lifetime associated with it? The lifetime makes it difficult to use in structs, as I then need to add a lifetime to them. I see that ...
1
vote
2answers
41 views

Is there a way to impl trait for a tuple that may have any number elements? [duplicate]

I have a trait like this: trait Foo { fn do_somthing(self) -> Self; } And I want implement this trait for a tuple that may have any number of elements that implement this trait. impl<T>...
1
vote
1answer
39 views

Graceful exit TcpListener.incoming()

From the rust std net library: let listener = TcpListener::bind(("127.0.0.1", port)).unwrap(); info!("Opened socket on localhost port {}", port); // accept connections and process them serially for ...
0
votes
1answer
45 views

how to layout my Rust modules in src for access across my application

I have created a package structure but the compiler says it can't find my module. I am new to rust, with a background in Java & C# I have tried using self and super prefixes but can't get the ...
1
vote
3answers
40 views

How to pass a PrimInt to multiple threads?

I would like to write a function that accepts an integer, and spawns threads that use this integer. The integer could be computed. It doesn't need to be a literal. If I use a concrete type such as ...
0
votes
1answer
36 views

How can I call a variadic C function with a list of arguments pulled from a rust Vec? [duplicate]

I am trying to call the JNI function CallStaticVoidMethod from rust. The jni-sys wrapper declares it as pub CallStaticVoidMethod: Option<unsafe extern "C" fn(env: *mut JNIEnv, cls: jclass, ...
0
votes
1answer
34 views

How can I extend the lifetime of a temporary variable inside of an iterator adaptor in Rust?

I have a method make_iter() which creates an Iterator with multiple adapters in Rust, which can be simplified as the following MCVE: fn make_iter(first: &First) -> Box<dyn Iterator<Item =...
0
votes
2answers
51 views

How is returning a variable “let” inside a function allowed in rust?

This example compiles and returns the "expected" output. But is this not a dangling pointer scenario? If so, how come the rust compiler allows this? use serde_json::{Value, json}; use std::io::Result;...
0
votes
1answer
20 views

Why do I get “unexpected token” when trying to call an inner macro with the argument of an outer macro?

I don't understand this failure while trying to pass the expression received by the higher! macro to the lower! macro: // A low-level macro using only Rust primitives. macro_rules! lower { (x, $a:...
1
vote
1answer
19 views

the trait `serde::Deserialize<'_>` is not implemented for `diesel_geography::types::GeogPoint`

I'm trying to use Diesel and diesel_geography to read from a PostGIS database using Rust. Here's the error I'm getting: error[E0277]: the trait bound `diesel_geography::types::GeogPoint: serde::...
0
votes
0answers
25 views

How to Serialize context for Template::render

I'm trying to use Handlebars with Rocket and Diesel. Unfortunately I didn't get this combination to work. First I build a simple rest-API using this tutorial. Then I tried to test a handlebars-...
0
votes
0answers
22 views

are the pointers extracted from rust's CString living long enough to still be valid when JNI_CreateJavaVM is called?

I am trying to figure out how to create a Java VM from a rust program so I can use the batik library to render some SVGs. So far I have the following code: extern crate jni_sys; use std::os::raw::{...
0
votes
0answers
33 views

Pass file from Javascript to u8 in Rust WebAssembly

I want to pass through a file from JavaScript and get access to it as a u8 array in Rust WebAssembly. I have done this in Emscripten c++ buffer by allocating memory and passing pointer but I can't ...
0
votes
1answer
51 views

is there a trait to read from stdin or from file in rust?

As a newbie on rust i wonder to know if there is way to use a single function/macro/anything-else to read a line from a passed file or from stdin, passing as argument a kind of buffer reader maybe? I ...
0
votes
1answer
34 views

Parsing JSON response from request GET call asynchronously

I am making a GET call to some API which in turn would return me list of JSON objects. However, I couldn't parse this into list of custom data structure. Closest I could come to struct Pokemon { ...
0
votes
0answers
53 views

How can I move bytes from a slice into the middle of an array without cloning

I'm trying to overwrite the payload of a packet. I currently have the following code, it works but benchmarking via perf has shown that cloning the payload of every packet has a significant overhead. ...
8
votes
1answer
94 views

Why does 'if let' block the execution with usage of Mutex?

I have bumped into this deadlock scenario while working with Mutex The struct that contains a field of Mutex type is as follows: struct MyStruct { inner_map: Arc<Mutex<HashMap<i32, Vec&...
2
votes
2answers
28 views

How to access modules from parent or sibling folder modules?

I am trying to access modules from the parser.rs and another.rs in the solve.rs. How to include those modules and use the "use statements"? If that is not possible what should be the code structure? ...
0
votes
0answers
47 views

Dynamically determine enum type in Rust

I am reading the docs on strum crate. It is mostly about getting the enum VARIANTs out from a string. Is it possible to get the enum type from a string. Specifically, is the following possible? ...
0
votes
0answers
29 views

Nested Future Chain not calling inner Future for Rusoto RusotoFuture

I'm trying to use rusoto to get a list of files via ListObjects call on it's S3 crate, however when I chain it's output to the next set of futures the inner futures don't seem to be called upon, I've ...
1
vote
1answer
66 views

A Hashmap supporting String and &str

How do I define a HashMap supporting both String and &str in its key and content? I tried the following: fn mapping<T: Into<String>>() -> HashMap<T, T> { let mut map: ...
2
votes
1answer
70 views

Why does this closure argument need an explicit type? [duplicate]

Consider the following working code: fn f() { let xs = vec![(0, 0)]; let f = |j| xs[j]; let y = f(0usize); } The following variation does not compile: fn f() { let xs = vec![(0, 0)];...
0
votes
0answers
38 views

Why does the compiler alert me about a mutable borrow after a while let loop goes out of scope? [duplicate]

full code pub struct List<T> { pub head: Option<Node<T>>, len: usize, } impl<T> List<T> { pub fn new() -> Self { List { head: None, len: 0 } }...
1
vote
1answer
26 views

Exposing vanilla Rust classes with wasm_bindgen

I am learning how to target WASM with Rust through this tutorial. I want to be able to separate my domain code from the code that exposes it to WASM. That way, I could re-use the domain code in a non-...
-1
votes
1answer
26 views

How do I return the result of get_mut from a HashMap or a HashSet?

I'm trying to wrap a HashMap, as defined below, to return a mutable reference from a HashMap: use std::{collections::HashMap, marker::PhantomData}; struct Id<T>(usize, PhantomData<T>); ...
2
votes
1answer
53 views

How to clone a Generator?

Is it possible to clone a variable of type std::ops::Generator? There is a generator, I want to create a new instance, with a clean stack, there is no clone() method. I tried inside Box and inside Pin,...
0
votes
0answers
39 views

How to create a global HashMap? [duplicate]

I created a static mutable HashMap at the beginning of the file, hoping to use it as a global variable, however I didn't find anything on this beyond "static variables are global variables". There is ...
0
votes
2answers
61 views

Is it possible to collect an iterator to populate a collection backwards?

Is it possible to collect an iterator such that it populates a collection backwards, such as using push_front in a VecDeque? It's possible to collect into a Vec and then reverse it, but it seems like ...
0
votes
0answers
15 views

Multiple binaries project - how to include common parent module [duplicate]

I have a cargo project with two different binaries, in my Cargo.toml file I defined: [[bin]] name = "server" path = "src/main.rs" [[bin]] name = "client" path = "src/bin/client.rs" And my project ...
0
votes
1answer
31 views

How do you specify the LD_LIBRARY_PATH for a rust project in IntelliJ IDEA?

I am using IntelliJ IDEA to experiment with rust. In order to gain an understanding of how to invoke libraries created in other languages, I have created a tiny dynamic library in C whose .so file is ...
0
votes
1answer
36 views

Why can't I divide a BigInt with another BigInt and save it to a variable I've initialized with zero?

I have the following code snippet: use num_bigint::*; // 0.2.2 use num_traits::*; // 0.2.8 use std::ops::*; fn xgcd(b: &BigInt, a: &BigInt) -> (BigInt, BigInt, BigInt) { let mut x0: ...
-2
votes
2answers
39 views

bash: gdb: No such file or directory

I am following the official documentation of Discover Rust. I am trying to flash the program into STM32F3. The Flash chapter asks to execute this command <gdb> -q target/thumbv7em-none-eabihf/...
-1
votes
0answers
26 views

How to use modules that are multiple levels above a file?

I'm trying to access code that's multiple levels above the file I'm in. My file structure looks like: top --utils ----file_I_want_to_use.rs --one ----two ------three --------...
0
votes
0answers
31 views

Best way to process complex Rust command line arguments? [on hold]

Currently, I have a Rust program that takes in some complicated command line arguments and I'm parsing them using: use std::env; fn main (){ let args : Vec<String> = env::args().collect();...