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].
Currently, working on learning parallelization and am investigating why a test program I wrote is not scaling well. I have a simple program that does a CPU bound computation through L iterations and ...
egerhard
89411 gold badge88 silver badges1616 bronze badges
I am studying Rust and upon working on the Guessing Game I found this odd behaviour:
use std::io;
fn main() {
println!("Welcome!");
let mut input = String::new();
print!("...
khuynh
1,24911 gold badge88 silver badges1717 bronze badges
I have an (acyclic) tree structure using some structs. I want to codify the relations at the type-level so I can get guarantees on whether a given struct is a descendant of another.
Would it be ...
Tails
37422 silver badges1212 bronze badges
I've been trying to impl the push for this struct:
struct StackMin<T: std::cmp::Ord>
{
stack : Vec<T>,
min : Vec<T>
}
like this:
fn push(&mut self, item: T) {
let l =...
marc_s
671k157157 gold badges12461246 silver badges13791379 bronze badges
Is there any case where one would use str without borrowing it? Does that even make sense?
I understand the difference between String and &str, but since there is &str there must also be str?
marc_s
671k157157 gold badges12461246 silver badges13791379 bronze badges
I'm using mongodb and I have a function to increment a field called "id" by 1.
let mongo_colecction = conecction_bd::my_bd_collection("AutoCode").await?;
let filter = doc! {
&...
Daniel
10711 silver badge77 bronze badges
I have a problem to store date & time into mongoDB in Rust.
I use the official Rust mongodb Driver, chrono crate and serde serializer/deserializer
let doc = doc! {
// this make "timestamp&...
kmdreko
13.8k33 gold badges1919 silver badges4141 bronze badges
I want to set a top level const in a Rust file to the value of an environment variable. In something like nodejs which I'm more used to, I would do something like:
const my_const = process.env['...
Denys Séguret
332k7373 gold badges715715 silver badges694694 bronze badges
I might be using the wrong terminology here because I'm unfamiliar with Rust but essentially I'm trying to wrap a C library with safe Rust functions like this:
use std::os::raw::c_int;
mod c {
...
I'm trying to convert the C++ COM code for TaskScheduler to Rust and am stuck with the VARIANT argument of ITaskService::Connect:
extern crate winapi;
use winapi::{
ctypes::c_void,
shared::{
...
Jannis Froese
1,14711 gold badge88 silver badges2020 bronze badges
I have a struct that I want to contain a vector of a "base class" jobs (there are sub-classes for different job types). In rust, I would think to implement this as a vector containing a ...
cpage
2733 silver badges1414 bronze badges
Is it possible to set the default target for Cargo builds on a per-platform basis?
I want cargo build to target the Musl target when building on Linux, without having to specify it in a CLI option/...
Timmmm
66.7k5050 gold badges279279 silver badges352352 bronze badges
I started learning Rust today and I don't get why I've got the warning below:
warning: field is never read: `x`
--> main.rs:62:9
|
62 | x: f64, //Float com 64-bits
| ^^^^^^
...
Shiva
1,5081515 silver badges2525 bronze badges
I'm trying to deserialise a binary format (OpenType) which consists of data in multiple tables (binary structs). I would like to be able to deserialise the tables independently (because of how they're ...
I'm having trouble initializing a fixed length array. My attempts so far all result in the same "use of possibly uninitialized variable: foo_array" error:
#[derive(Debug)]
struct Foo { a: u32, b: ...
Consider this C++ code:
#include <iostream>
#include <functional>
using namespace std;
std::function<int(int, int)> foo(int c) {
auto add = [] (int a, int b) { return a + b; };
...
Ivan C
87911 gold badge22 silver badges99 bronze badges
I'm working with the smartcore library in rust. Trying to delete the last column from a DenseMatrix.
I thought maybe of creating an identity matrix with the right columns and rows. but didn't really ...
Ratah
19411 silver badge1010 bronze badges
Recently, I am reading source code in the repo parity-bridges-common. There are some rs files full of incomprehensibly asynchronous syntax that I am not familiar with. Especially about FusedFuture. ...
I have functions that return an Option or a Result:
fn get_my_result() -> Result<(), Box<Error>> {
lots_of_things()?;
Ok(()) // Could this be omitted?
}
fn get_my_option() ->...
Milack27
9951212 silver badges2323 bronze badges
What is the best way to do this:
I have a 2GiB memory block that needs to be initialised with some data.
Data are all independent, so I can easily spawn n threads to initialise the data in parallel ...
user4815162342
102k1212 gold badges174174 silver badges244244 bronze badges
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] // ...
I'm trying to use the actors as documented in the actix documentation. But even the doc example is not working for me. I tried the following code which compiles but does not print the message "...
b.moyet
8511 silver badge99 bronze badges
I need to create an iterator that owns the value (allows to wrap the trait object to Rc) and return it as next() value (playground):
use std::rc::Rc;
use std::collections::HashMap;
trait TProduct {
...
Masklinn
15.1k11 gold badge1010 silver badges2929 bronze badges
I'm writing a virtual machine that executes instructions one by one and also can jump forward and backward.
For example, if it has a list of instructions [A, >B, C, D] and currently is at ...
Denys Séguret
332k7373 gold badges715715 silver badges694694 bronze badges
Does rustc optimize such expressions?
2*x -> x<<1
x/2 -> x>>1
x % 8 -> x&7
and such
Inline
1,75599 silver badges2424 bronze badges
I am trying to get started with Rust, and wondered how the following piece of c++ code can be converted to rust.
Consider this C++ code:
void func(int c) {
unordered_map<int, int> map;
auto&...
Inline
1,75599 silver badges2424 bronze badges
Hopping between languages can be painful. Idioms of one language "feel good" and one starts to look for the same idioms in other languages.
In F#, there is a way to init an array with the help of a ...
Netwave
23.6k44 gold badges3030 silver badges5858 bronze badges
I have this "main.rs" file which I declare a version constant.
pub const VERSION: &'static str = "v2";
mod game;
fn main() {
do_stuff();
}
Then I want to access this global constant in a ...
Canato
2,07811 gold badge2424 silver badges4444 bronze badges
fn reveal_vote(phrase: Vec<u8>, hash: Vec<u8>) {
}
I want to check hash of the phrase matches with hash submitted as Vec<u8>.
I tried using hex and sha3 package. But both hex and ...
Given a Box holding a dyn Trait object, is there any way to construct a Boxed unsized type?
For example, suppose I have a (potentially) unsized type:
pub struct IdAndData<T: ?Sized> {
id: ...
Kevin Reid
20.3k99 gold badges5858 silver badges8282 bronze badges
I playing with the Rust code, and I've got to a place in which I have a problem with converting Option<&[u8; 32]> to Option<&[u8]>.
A (very) simplified example:
pub type Foo = [u8; ...
Denys Séguret
332k7373 gold badges715715 silver badges694694 bronze badges
I'm trying to design a simple serialization function:
pub fn serialize(buffer: &[u8]) -> std::result::Result<(), ()> {
Ok(())
}
the above is not ok because the buffer ...
kmdreko
13.8k33 gold badges1919 silver badges4141 bronze badges
Is there a way to overwrite console output using Rust instead of simply appending?
An example would be printing progress as a percentage; I would rather overwrite the line than print a new line.
How about this?
fn my_sum(ns: &Vec<usize>) -> usize {
match ns.split_first() {
None => 0,
Some((n, ns)) => n + my_sum(&ns.to_vec()),
}
}
I wanted to use ...
Stargateur
16.9k77 gold badges4242 silver badges6767 bronze badges
On https://tools.ietf.org/html/rfc7230#section-3.2.6 it says:
The backslash octet ("\") can be used as a single-octet quoting
mechanism within quoted-string and comment constructs. ...
Gatonito
53211 gold badge77 silver badges2626 bronze badges
There is a known problem of search of the middle node of a linked list:
Given a non-empty, singly linked list with head node head, return a middle node of linked list.
If there are two middle nodes, ...
I want to change button's label when button is pressed.
But I got this error message.
error[E0505]: cannot move out of `but` because it is borrowed
--> src/main.rs:24:22
|
24 | but....
MoDev
2811 silver badge55 bronze badges
The title says it all. I want to generate the alphabet as a vector of characters. I did consider simply creating a range of 97-122 and converting it to characters, but I was hoping there would be a ...
Alex V
3,01611 gold badge2424 silver badges4343 bronze badges
When defining a generic struct, is there a way in Rust to use different implementation of a method according to which trait is implemented by the given generic type T?
For example:
struct S<T> {
...
This code serializes an array of 32 bytes exactly as I want:
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
struct Hash([u8; 32]);
let hash = Hash([1u8; 32]);
let ...
fadedbee
37.7k3939 gold badges140140 silver badges234234 bronze badges
Is there a format specifier that will truncate a string-like type? I have a type which is not a String, but does implement Display. I want to limit it to be 7 characters long though, and the only way ...
Michael Dorst
6,3791010 gold badges3535 silver badges6464 bronze badges
In the code below I have a struct Foo with two fields a and b. When borrowing the separate fields directly from the struct there's no issue borrowing. However, when I hide the borrow behind a method ...
I have a program that uses std::process::Command::spawn, and it produces zombies.
I know very well that the parent process must read out children exit codes, otherwise zombies happen. This is also ...
ulidtko
12.3k99 gold badges4747 silver badges8282 bronze badges
My very first rust program/function is supposed to walk a dir tree and deliver a HashMap with K(mime_as_string) and V(count_sum, size_sum). And I want it in FP style.
So what I have is this:
fn ...
user2722968
7,83222 gold badges2323 silver badges4848 bronze badges
I need to add some custom metadata to a PDF file that should be hidden from end users.
Then I need to extract this metadata (to process it in another app) and be able to restore the original file (I ...
struct Z;
struct S<N>(N);
struct MinHelper<N1, N2>(N1, N2);
trait Min {
type Val;
}
impl<N1> Min for MinHelper<N1, Z> {
type Val = Z;
}
impl<N2> Min for ...
Boann
44.7k1313 gold badges105105 silver badges136136 bronze badges
I am doing my assignment that's include make connection with the database in Rust. I am using the latest version of mysql crate: mysql ="18.2.0".My Database connection is successful as I ...
CapelliC
57.5k44 gold badges4141 silver badges8080 bronze badges
I'm trying to implement the Partition function (number theory)
Hardy-Ramanujan formula
for partitions in Rust.
I try like this:
fn partitions(n: f64) -> f64 {
let pi = 3....
Consider the following code (also available on the playground)
pub trait TextStream {
fn next_str(&mut self) -> Option<&str>;
}
pub struct FilterTextStream<T: TextStream> {
...
I need to do the same operations as in Some(Md5Sess), changing only the type that calls digest. So change from <md5::Md5>::digest to <sha2::Sha256>::digest etc and possibly many others:
...
Emoun
1,07211 gold badge44 silver badges1414 bronze badges