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.

1
vote
1answer
15 views

How can I populate a vector in reverse?

I've got a vector: let v = Vec<T>::with_capacity(10); I want to populate it with data, in reverse order: let i = 10; while i > 0 { i -= 1; v[i] = non_pure_function(i); } ...
0
votes
1answer
13 views

How to give a reusable name to a multiple type bound in a Rust generic function

Take the following code fn do_stuff<T: ?Sized + io::Write + io::Read>(mut serial: Box<T>) { // stuff } It can take for example a serial device to work with, or maybe a file for testing ...
0
votes
0answers
7 views

Reexport auto-generated FFI functions

I'm writing a binding for a C library with help of rust-bindgen for which the function signatures are generated automatically into a bindings.rs as: #[repr(C)] struct A { ... } struct B { ... } ...
-2
votes
0answers
22 views

iter method for lifetime referenced string

I have the following code: #[derive(Debug, PartialEq, Eq, Copy, Clone)] pub struct Trip<'a> { pub cod: &'a str, } #[derive(Debug, Clone, Copy)] pub struct ami<'a> { pub tlc: &...
0
votes
1answer
27 views

How to push an element to the last vector in a vector of vectors?

I am trying to access the last vector in a vector of vectors (Vec>) and push a value to it, but I continue to come across errors. A simplified version of what I am trying to do is: let mut pc: Vec&...
-1
votes
0answers
49 views

Why does the compiler not complain when you don't write the full path for enum pattern matching? [duplicate]

When I define a enum like this: enum MyEnum { one, two, three, } and match like this: let n = MyEnum::two; match n { one => println!("one"), two => println!("one"), ...
0
votes
0answers
39 views

How do I return a trait object with generic methods?

I am using yup_oauth2 and attempting to create a Token source that implements the GetToken trait for use on Google Compute Engine. pub trait GetToken { fn token<'b, I, T>(&mut self, ...
-2
votes
0answers
22 views

Combine two RefMuts

I have a struct with two vecs wrapped in RefCells. I want to have a method on that struct that combines the two vecs and returns them as a new RefCell or RefMut: use std::cell::{RefCell, RefMut}; ...
-1
votes
0answers
22 views

Rust global const of struct not persisting pointer address [duplicate]

I am building a struct called DATAMAP which is designed to hold a vector of TCPStreams. After I declare the struct, I proceed to instantiate a global const reference to it. The issue I am having ...
0
votes
0answers
39 views

How can I take two mutable borrows from different parts of a vector? [duplicate]

Let's say I want to swap the first and third items of a vector using a bit-twiddling hack: fn main() { let mut v = vec![0, 1, 2, 3, 4, 5, 6, 7]; { let first_item = &mut v[0]; ...
-1
votes
0answers
34 views

Is there any way to convert std::io::Error to failure::error::Error?

I have this code: let file = FileStorage { // ... }; file.write("Test", bytes.as_ref()) .map_err(|e| MultipartError::Payload(error::PayloadError::Io(e)))?; It doesn't really matter in which ...
-1
votes
0answers
38 views

trait `postgres::types::FromSql` is not implemented for `bit_vec::BitVec` [duplicate]

I have following data structure #[derive(Serialize, Debug)] pub struct TestEvent { id: i32, event_mask: bit_vec::BitVec } While fetching value for this field from database, I am getting ...
-1
votes
0answers
56 views

Call immutable function from mutable function in Rust [duplicate]

I have some structs: struct data { payload: i32, } struct bar { datas: Vec<data>, } impl bar { pub fn f2(&self, dta: &mut data) { dta.payload = 1; } pub ...
0
votes
1answer
36 views

Is there a safe way to reuse the same code for immutable and mutable variants of a function? [duplicate]

I did a bit of searching, and found this Reddit post from four years ago, but other than unsafe code: fn find_mut <'a> (&'a mut self, elem: &T) -> Option<&'a mut Node<T>&...
0
votes
1answer
38 views

How to save ndarray in Rust as image?

I have ndarray let mut a = Array3::<u8>::from_elem((50, 40, 3), 3); and I use image library let mut imgbuf = image::ImageBuffer::new(50, 40); How could I save my ndarray as image ? If ...
1
vote
0answers
37 views

Unable to use parity_codec's Encode even though I have derived it for a struct

I am trying to use Encode::encode on structs with a derived implementation, but I am getting this error: error[E0599]: no method named `encode` found for type `AnimalCollection<Animal>` in the ...
0
votes
0answers
19 views

Running LLC from rust results in undefined reference to `main' for linking with gcc

Consider the hello world in LLVM-IR @.str = internal constant [14 x i8] c"hello, world\0A\00" declare i32 @printf(i8*, ...) define i32 @main(i32 %argc, i8** %argv) nounwind { entry: %tmp1 = ...
1
vote
2answers
97 views

Lifetimes in generic trait implementation

I want to make a trait similar to the below structure (my particular use case is a bit more complex but this captures the issue and error I'm getting). The issue I have is which lifetimes in the last ...
-2
votes
2answers
51 views

Remove Vec product second mutable borrow occurs here

I have a list (sprites: Vec<RefCell<Sprite>>) in a structure I have to add objects and remove them, no problem to add, but impossible to remove add objects pub fn _clean() {} fn ...
1
vote
1answer
23 views

Does the Tokio reactor poll all possible poll() functions between each combinator?

A call to poll can never block, otherwise the entire thread the async core executes on will be blocked, stopping all possible causality until the blocking function returns. I spawn a future onto the ...
1
vote
0answers
18 views

“Recent HTTP errors” not displaying in Traefik dashboard

Recent Http Errors are not displayed on our Traefik dashboard. I have included http statistics as according to the documentation: https://docs.traefik.io/configuration/api/#metrics [https] [http....
0
votes
1answer
196 views

Why is it impossible to dereference a boxed iterator trait object? [duplicate]

I have three following examples: fn iterate_with_iterator<T: std::fmt::Display, I: Iterator<Item = T>>(iter: I) { for x in iter { println!("{}", x); } } fn ...
0
votes
1answer
44 views

How to build a dependency with a different version of the Rust compiler?

I've got a Rust project I build with the 1.33 tool chain. I need to add a dependency on a crate that can only be built with Rust nightly, how can I specify in the dependencies it should be built with ...
0
votes
1answer
40 views

How can I represent this data?

My previous question on this topic has been correctly identified as an instance of the XY problem. I'm trying to create a resource management crate to decide who gets to rent the flooble. The public ...
1
vote
0answers
21 views

How to log into phpmyadmin with rust http requests

I'm a beginner at rust so pardon my mistakes. I'm trying to log into my teams phpmyadmin server to webscrape some SQL data, but I'm unsure on how to proceed. I've managed to get request the login ...
0
votes
1answer
20 views

How to get a nested property from serde_yaml::Value?

I have the following YAML file version: '3' indexed: file1: "abc" file2: "def" file3: 33 I read it with this code: pub fn read_conf() -> Result<(), Box<dyn Error>>{ let f = ...
0
votes
1answer
52 views

How do you convert Vec<&mut T> to Vec<&T>?

I've got a vector of mutable references: type T = String; let mut mut_vec: Vec<&mut T> = vec![]; I want to pass (a copy of) it into a function that takes a vector of immutable references: ...
0
votes
0answers
29 views

Cargo cannot download dependencies

I'm trying to build local Rust projects with dependencies from various crates using Rust 1.35.0 on Windows 10 x64. Every time I try to run cargo build or cargo run the following error message appears. ...
0
votes
0answers
41 views

Why is `should_panic` an attribute and not a macro?

I wonder why we aren't using a function, or a macro, to test if a function will panic. From the book: In addition to checking that our code returns the correct values we expect, it’s also ...
-1
votes
1answer
72 views

Why does removing an unused `if` clause reduce execution time from 12ms to 4ms?

I'm using Rust to solve LeetCode problem 645 "Set Mismatch". The solution is to iterate over the array and find the duplicate, then add an error to the duplicate to find the missing value. Here's my ...
0
votes
1answer
39 views

Reference traits: no implementation for `&T * &T`

I try to write generic method and specify some type T: num_traits::float::Float from num-traits crate. How should I ask &T to implement basic numeric methods such as multiplication? use splines::{...
0
votes
1answer
57 views

How do I use the postgres crate to receive table modification events from PostgreSQL?

I have a Rust process dealing with a PostgreSQL database. This process communicates with a server process to pass on the details using MPSC channels. I am stuck on how to listen for and process events ...
0
votes
1answer
49 views

How to handle different error types after boxing them with Box<error::Error>? [duplicate]

In my try to better handle errors and prevent repeating tio much code, I am implementing the ?, operator returning Result<bool, Box<error::Error>> so that I could just match the error once ...
0
votes
1answer
63 views

Pest doesn't parse a recursive grammar as I would expect

I'm using the pest crate to implement a recursive grammar in Rust: id = _{ ASCII_ALPHA_LOWER ~ (ASCII_ALPHANUMERIC|"_")* } integer = _{ (ASCII_NONZERO_DIGIT ~ ASCII_DIGIT*)|"0" } real = _{ ((integer ~...
0
votes
0answers
33 views

srml_system::Trait::Hash equality comparison

How can I perform an equality comparison on substrate Hash trait? Say I have the following code, with owned_vec contains a vector of Hash: use support::{decl_module, decl_storage, decl_event, ...
-4
votes
0answers
36 views

is there a way to return a value from a for loop to then be implemented into a struct

Im trying to search for an ID after parsing a json and when doing so i want to be able to take the value from the for loop and return it to a varible so that later i can implement into a struct. i am ...
1
vote
0answers
33 views

Passing `self` reference while iterating through a member [duplicate]

I know in Rust, there can't be multiple reference to one object if one of them is mutable. So when I want to pass self as a reference inside a loop that is borrowing a member already, it wouldn't ...
2
votes
3answers
77 views

How should I store a list of items from which I will be removing, but never adding?

I'm implementing a function where I'll be repeatedly eliminating values from a large list, and passing a copy of this list as a vector into another function each iteration: let mut v = vec![5, 4, 4, ...
1
vote
1answer
52 views

How would I check if a directory is empty in Rust?

I'm working on a CLI tool that avoids clobbering an existing directory with existing files but doesn't care if the directory doesn't exist or is empty. I know I can use .exists() to see if the ...
1
vote
2answers
52 views

Ownership, closures, FnOnce: much confusion

I have the following snippet of code: fn f<T: FnOnce() -> u32>(c: T) { println!("Hello {}", c()); } fn main() { let mut x = 32; let g = move || { x = 33; x }...
-1
votes
0answers
17 views

Rust cargo.toml errors when using bin and lib [duplicate]

I have a rust project with the following cargo.toml : [package] name = "beefucurry-image" version = "0.1.0" authors = ["beefucurry <...>"] edition = "2018" [lib] name = "beefucurry_image" ...
2
votes
1answer
42 views

How can I display a compiler warning upon function invocation?

I've got a function I want to export in my module so people can use it. However, in ≈95% of cases, using it is a bad idea. /// Check whether foo is a metasyntactic variable. /// /// **Using this ...
1
vote
1answer
58 views

Is there a way to write to a whole row / column of a nalgebra Matrix?

I am using the DMatrix struct to allocate dynamically sized matrices, where I repeatedly overwrite each column by the normalized column vector, using the L2-norm. // a is some DMatrix of arbitrary ...
-3
votes
0answers
74 views

What's a convenient way of matching field names, parsing appropriate values, and setting the fields of the result struct using nom5?

I'm writing a nom 5 parser for a format based on structs with field names and values. The field names are determined by the format i.e. they're statically known and I don't need to look at them ...
-1
votes
1answer
59 views

Struct that has a value of a struct with a generic type [duplicate]

Suppose I have a struct that uses a generic type (BNO055 is a sensor): pub struct BNO055<T: I2CDevice + Sized> { pub i2cdev: T, pub mode: BNO055OperationMode, } I also have another ...
1
vote
1answer
64 views

How can I implement static cache in rust?

I want to implement a static cache in rust. I tried chashmap extern crate chashmap; extern crate lazy_static; use chashmap::{CHashMap, ReadGuard}; use lazy_static::lazy_static; use std::collections::...
0
votes
1answer
50 views

How can I implement traits for type aliases? [duplicate]

I have some code like this: type MyFn = Box<Fn(usize) -> bool>; fn main() { let my_fn: MyFn = Box::new(|x: usize| x > 10); dbg!(my_fn); } This doesn't compile because MyFn doesn'...
2
votes
1answer
41 views

Define a custom parser using structopt that changes based on another flag

I use structopt to parse the command-line arguments to my rust application. The flags in question are the following: query (positional), and case_sensitive (optional). #[derive(StructOpt, Debug)] pub ...
0
votes
1answer
38 views

How to write fuctions that takes IntoIter more generally

I was reading an answer to stackoverflow question and tried to modify the function history to take IntoIter where item can be anything that can be transformed into reference and has some traits Debug ...
1
vote
1answer
38 views

Can't make basic example of Serde Serialize work

Serde documentation says: All of these can be serialized using Serde out of the box. serde_json is just for the example, not required in general. This is exactly what I need, a basic ...