Redundancy_

u/Redundancy_


r/learnrust•

I'm trying to understand how I can solve a particular problem that I have -

I need to have a dynamic (runtime) handler for callbacks from some C++ - this is fine, I can use a dyn trait in a box, put whatever handler I want in there. However, I want to be able to get at the object that I put in there, to pull a type-specific object that it builds from those callbacks back out of it.

So I have:

pub trait CallbackHandler: Any {
    fn callback(&mut self, message: &str);
}

pub struct UICallbackProxy {
    value: Option<Box<dyn CallbackHandler>>,
}

then:

// JsonValueCollector implements CallbackHandler
ui.callback.value = Some(Box::new(JsonValueCollector{ va
23

r/rust•

I work in a domain where we more than occasionally deal with web requests that touch on purchases that people make. We need to go out, check their state, redeem purchases etc.

This is where Rust Async, and particularly cancellation, makes me nervous: In the realm of purchases, not giving something to a person who purchased it is bad. It can be taken to various legal venues in countries, and so it's important not just for the user experience, but legally, to try to ensure that you do everything you can to ensure that you either give the user what they bought, or ensure that you enable it to be recoverable.

Now imagine a Rust web server that's handling those things in an async context - if

2039

r/rust•

I've been fairly curious about the behaviour of async since I started to explore it, and a more recent post on here about async cancellation made me wonder what the behaviour of web servers was.

I did a little hello world test in axum:

let app = Router::new().route("/", get(|| async {
        println!("Before");
        tokio::time::sleep(time::Duration::from_millis(500)).await;
        println!("After");
        "Hello, World!"
    }));

...

If hyper/axum don't cancel execution when a client disconnects, you'd expect a "Before" and "After" log for every request, but if they do, then you'd expect to sometimes see only "Before" if the client is set up to t

66

r/learnrust•

I'm looking at different ways to represent a map (static graph) in Rust, and I'm running into something that I can't quite grasp.

When I make a vec, everything within it has the same lifetime, which means that I can use borrows of different items to build the graph.

This works fine until I attempt to move an Arc of the Vec onto another thread, at which point the references lifetimes are no longer ok.

use std::sync;
use once_cell::sync::OnceCell;
use sync::Arc;

#[derive(Debug)]
struct Item<'a> {
    name: String,
    neighbours:  OnceCell<Vec<&'a Item<'a>>>
}

fn main() {
    let solar_systems = Arc::new(vec![
64

r/learnrust•

I'm writing a toy pathfinder in Rust, using the Eve Online static data export as a "map".

It's been interesting downloading the export, streaming the zip files to memory, extracting the data needed and constructing enough to eventually do some pathfinding on (still todo).

My main current data-structure looks like this:

#[derive(Debug)]
pub struct SolarSystem {
    pub name: String,
    pub solar_system_id: SolarSystemId,
    pub constellation_id: u64,
    pub region_id: u64,
    neighbours: once_cell::unsync::OnceCell<Vec<Weak<SolarSystem>>>,
}

contained in a Vec.

I needed a once-cell/RefCell etc to do the linking of the solarsystems (t

313

r/learnrust•

I'm trying to make a type that is limited to the values 1-9 for a sudoku solver.

It made sense to me to implement a TryFrom<u16>, but I thought that it might be even better to implement TryFrom for anything that can Into<u16>

TLDR implementation:

fn main() {
    let a: board::Cell = board::Cell::try_from(1u16).unwrap();
    println!("{:?}", a)
}

mod board {
    #[derive(Debug)]
    pub struct Cell(u16);

    impl<T: Into<u16>> TryFrom<T> for Cell {
        type Error = ();

        fn try_from(value: T) -> Result<Self, Self::Error> {
            let v: u16 = value.into();
            i
55

r/learnrust•

This is a follow-on question to https://www.reddit.com/r/learnrust/comments/uqgr4e/hoping_for_feedback_on_snippet_exercism_forth/ although it probably isn't necessary to look at the prior post.

I'm trying out some different patterns for managing my Vec<String>s and iterators rather than trying to have the iterators own the strings.

Is there a pattern where I can immutably borrow elements in a container that can have new items added to it?

As an example, imagine (or refer to the link above) a loop over a chain of iterators. New items can be added and chained in from `Vec<Stri

13

r/learnrust•

https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=489be0f116db94aa85f2ff56dcd05b11

Playground link to the code. Tests from the exercise included. Everything should pass when run under test.

Although the exercise is completed, I'm looking for some feedback for improvement. For some reason I can't submit it on Exercism at the moment (gets a kill signal).

The major area where I'm not feeling particularly comfortable is the ":" clause - I had to do a number of contortions like while let Some(i) = &stream.next`

31

r/learnrust•

I have some code that uses a trait to define what I need from a container type, with the intent that the container could be specifically optimized for the use case.

I picked some names for things that I wanted, such as push() for adding elements. When I was writing my tests, I noticed that I wasn't hitting my breakpoints because it was picking up push from the underlying type.

None of this is a particular problem, because I could fully qualify which push I need, but it did raise a question for me on convention - should I be:

  1. picking trait method names that aren't likely to overlap with existing implementations given potentially different post-conditions
  2. fully qualifying the imple
21

r/learnrust•

https://docs.rs/reqwest/0.11.3/reqwest/struct.Response.html#method.bytes_stream
https://docs.rs/zip/0.5.13/zip/read/fn.read_zipfile_from_stream.html

I was looking into downloading and unpacking a select amount of a zip without keeping all of it around, and came across these two things.

In one, reqwest is exposing a futures::stream::Stream and in the other, the zip crate is expecting an std::io::Read trait.

Is there some context around this in general? I understand why you might expose the body in a streaming fashion in terms of th

13

r/learnrust•

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=ef95c84f4358107e1bee95f1cae49f57

I solved my previous problems with implementing an enum that supports polling different types of async results, but now I'm running into a lifetime problem.

My thinking is as follows -

(L78) I hold on to the enum values in the remaining futures vec.

(L84-85) We get the values back from select_all in .2 minus the one that completed, and move that back into our remaining_futures variable. next is the value of the future that completed.

(L90) we match and move the value of a ReadDir to rd.

Calling next_entry will be a reference to rd, so we need to ensure that the Re

67

r/learnrust•

I've got a number of little rust projects on the go to try and learn the language better, but based on what I normally do in other languages I'm most interested in async use-cases.

I've been slowly trying to work through what seems like a relatively small problem - walking a directory tree using tokio in an async manner printing paths. I'm somewhat ignoring the question of if this is useful as a thing in itself, and just using it as a way to explore problems and learn -
- it doesn't require much code or explanation
- anyone can replicate it
- it seems like it touches on some fairly foundational issues that you have to understand
... essentially it's almost a self-designed asyn

39

r/golang•

I work at a company that is primarily based on Perforce for version control (there are good reasons, and it's not really useful to debate a change), and we've been doing fine for a while using a mono-repo and vendoring, but with more teams coming online we're starting to hit questions about how we share code.

My understanding is that the Go module download API is actually somewhat SCM agnostic (source: https://docs.gomods.io/intro/protocol/ ) so if we can use that it potentially side-step what Go supports.

I still find myself with a quandary however - since most of the proxies assume the same thing as Go, what's the best way to get our libraries i

11

r/golang•

I have a use-case where my team is developing Go code in a VCS that isn't one of the ones that Go supports integrations with. I'd like to be able to share and import code inside my organization's network.

I've noticed that the Go documentation is fairly vague at times about this topic:

If you keep your code in a source repository somewhere, then you should use the root of that source repository as your base path. For instance, if you have a GitHub account at github.com/user, that should be your base path.

Note that you don't need to publish your code to a remote repository bef

20

r/golang•

I have a use-case where I may need to work with linux filepaths on windows, or vice-versa.

It looks a lot like the assumption that you only need to work with paths that match your operating system, while certainly mostly correct, means that my best way of doing this looks to be to duplicate the filepath package. It feels like there ought to be a better solution than that, like how in http and some other packages you can use the module level default functions or create an instance of a client with the settings you need.

Does anyone know a better way of dealing with this issue?

17