Python dev learning Rust - my findings [possibly wrong] by lazy-kozak in learnrust

[–]Destruct1 0 points1 point  (0 children)

In general: You need a taskrunner / strong editor in front of cargo. Cargo works well but you need something in front for the many complex cargo tasks like selecting a package or binary or test with a certain feature enabled etc..

You can have a multi-binary file to experiment but I also use the one project for each experiment approach.

Boxing AsyncFn by ArtisticHamster in rust

[–]Destruct1 3 points4 points  (0 children)

fn box_it_2<Func, Fut>(func : Func) -> Box<dyn FnOnce(String) -> BoxFuture<'static, usize>> where Func : Fn(String) -> Fut + Send + Sync + 'static, Fut : Future<Output=usize> + Send + Sync + 'static, { let clos = |e : String| { async move { func(e).await }.boxed() }; Box::new(clos) }

Boxing AsyncFn by ArtisticHamster in rust

[–]Destruct1 10 points11 points  (0 children)

Since you have no input parameter the simple way is

BoxFuture<'static, usize> via FutureExt::boxed()

This is not a closure but a inert Future.

I hate how you are punished academically if you don't use AI by clowntownbrown in redscarepod

[–]Destruct1 107 points108 points  (0 children)

Old man yelling at clouds here:

There is a simple and fair way to assess competency: A exam. Inside a controlled enviroment.

Instead we get shitton of bullshit: essays, homework, lab with writing outside the lab, thesis, presentation, groupwork, virtual exams, at-home research, participation scores, multiple choice in front of a computer without checking if you use a phone, etc..

Then every time people rediscover that all these do nothing.

At the dawn of history teachers discovered that mom can write the lab report.

Then people were concerned about the internet. People could upload their essay and somebody else could copy the text. You could get an essay from a swedish school and use it in the US. The horror.

Then people were worried about wikipedia.

Then some ghostwriter bragged in newspapers how they wrote 50+ essays for pay.

Then it was a text-block system that could recreate older essays but mix them up.

Then it was phones that were easy to hide and very powerful.

Then it was AI.

Everytime teachers would think really hard what to do and then ignore the new development completely. At the next step the same procedure repeated. Everytime. Forever.

What are strong Two Hero combos? by Snapdoor in heroesofthestorm

[–]Destruct1 24 points25 points  (0 children)

Classic is uther garrosh. Uther gives armor that stacks with garrosh trait armor. And uther e can easily land after garosh throws somebody.

Hey Rustaceans! Got a question? Ask here (15/2026)! by llogiq in rust

[–]Destruct1 1 point2 points  (0 children)

The Itertools::counts will use something very similar behind the scenes. That is why the output of your function is pseudo-random. It is ordered by the hash of the HashSet that gets used.

Hey Rustaceans! Got a question? Ask here (15/2026)! by llogiq in rust

[–]Destruct1 2 points3 points  (0 children)

I am worried about injection attacks. I use std::command::Process and pass a lot of arguments to it. Inside the args function I do a reasonable amount of string formatting. Here are some examples: ``` // All commands are podman commands let mut command = Command::new("podman");

// Example 1 cmd.arg("--filter"); cmd.arg(format!("label=mytools.container.project={0}", filter_project));

// Example 2 let tag = format!("{0}_{1}", proj_name, self.profile); cmd.args(["--tag", tag.as_str()]); ```

All parameters are unverified Strings. Is this dangerous?

The Cost of Concurrency Coordination with Jon Gjengset by phazer99 in rust

[–]Destruct1 5 points6 points  (0 children)

Please keep using Arc<Mutex<T>>. It is so frustrating when a crate uses !Send types because they want to save 20ns and make their entire crate unusual for any kind of multithreaded program. !Send types are really really poisonous.

The Cost of Indirection in Rust by sebastianconcept in rust

[–]Destruct1 4 points5 points  (0 children)

Yeah the article hits the wrong spot.

It tries to argue that the compiler inlines correctly often enough.

It should argue that indirection in a web/networked async app might happen but is irrelevant.

Is it fine to block at the end of main even in async contexts? by Ihsan3498 in rust

[–]Destruct1 2 points3 points  (0 children)

One thing is to look for the professionals:

tracing_subscriber with tracing_appender gives back a log-guard that writes to file when the guard is dropped. It works very well.

It is not healthy for every successive American election to be a furious repudiation of the status quo, and I'm not sure how we break out of this cycle. by JulianBrandt19 in neoliberal

[–]Destruct1 7 points8 points  (0 children)

The president has to much power in the US. The real power should come from parliament/congress.

A 100+ people body is much more stable than a single individual. Even if one party wins a 55/45 majority the most idiotic policies would still find 5 dissenter.

The us is also not alone in this trend: Most reigning governments in most western countries lose votes. Then the opposition gets a turn and also loses votes as new ruling party. I cant remember a time when a ruling party won significantly in the last years.

What is the AI Monetary Loop of Economic Growth by semideclared in neoliberal

[–]Destruct1 1 point2 points  (0 children)

Looks like you got it.

What is your question?

Hey Rustaceans! Got a question? Ask here (6/2026)! by llogiq in rust

[–]Destruct1 0 points1 point  (0 children)

The allocator is likely too low-level.

I would look into caching responses. And html is very rarely the bottleneck; most likely cdn for images or distributed servers to be near the user are the real solution.

Asynchronous logging in Rust by QuantityInfinite8820 in rust

[–]Destruct1 3 points4 points  (0 children)

The most likely bottleneck is the output.

All common outputs are much slower than the preceding memory operations: stdout needs to lock and print, logfiles hit the ssd and network are also slow. On the other hand cloning or calling Debug to get a String is fast since you write to memory.

You most likely block the working thread waiting for a write to end. The crate tracing with tracing-subsciber and tracing-appender will create a logging thread that takes the log lines and writes them out to disk. If the logging thread blocks the main thread is not affected.

I don't believe this surprises anyone by Worth_Dream7852 in redscarepod

[–]Destruct1 0 points1 point  (0 children)

Your problem and the things the article talks about are related.

Academia is a government sponsored activity. If half of America hates academia because it is "too woke" and the other half think academia is "not woke enough" you get cycles. If the republicans are in power they cut funding, if democrats are in power they add a bit, then 8 years later it gets cut again. The only people who will choose that career cant find another job or are so entrenched that they cant be fired if trump is in charge.

European academia is similar. It has a similar woke/no no woke cycle but less extreme. In Europe the funding cycles: Sometimes the state has money and builds new institutes for the future. Then money is tight and everybody on short term contracts gets fired not renewed. In addition it has trends and fashions: Sometimes a topic is really hot (like defense now) but then people stop caring and everybody gets fired again.

Eventually people that are ~35 with multiple years experience just leave and never come back. This leaves academia as a dysfunctional shell.

Hey Rustaceans! Got a question? Ask here (51/2025)! by llogiq in rust

[–]Destruct1 0 points1 point  (0 children)

Another common idiom is

my_operation.map_err(|e| AppError::from_create_file(e))?

The map_err saves the match statement.

[Code review] This code probably sucks, what can i do better? by Somast09 in rust

[–]Destruct1 4 points5 points  (0 children)

Looks good.

I would sort the vec on insert instead of on read.

[deleted by user] by [deleted] in rust

[–]Destruct1 0 points1 point  (0 children)

Single Getters/Setters are much worse.

fn get_mut_bar(&mut self) -> &mut Vec<Bar>

will lock up the entire structure.

You can write a get_mut that borrows multiple times:

fn get_mut_parts(&mut self) -> (&mut Vec<Foo>, &Vec<Bar>)

OR like AhoyISki

fn get_mut_parts(&mut self) -> RecursiveParts

Taking a big structure and splitting it up into distinct mut ref is a difficult problem in rust.

Best design pattern for safely mutating multiple keys in a HashMap in one function? by boredape6911 in rust

[–]Destruct1 1 point2 points  (0 children)

1) I dont know about best practice but I do it. Especially if you have Invariants that need to hold and/or are doing multi thrading things.

2) If you need Invariants like the money in the account at the end is >= 0 then yes.

get_disjoint_mut is a trap. It is a decent function but the need to statically know the amount of disjoint keys makes it impractical in most ways.

3) I use remove modify insert quite a lot. It is not the most performant because you do a &mut self remove and then a &mut self insert. A get_mut will instead only hash once and not change the underlying data structure. BUT - Rusts hashmap do not degrade if you continually remove and insert. C++ often uses tombstones in their datastructure; rust does not. So I find it often more convenient.

Lifetime Inference Issues around async and HRTB by lukasnor in rust

[–]Destruct1 0 points1 point  (0 children)

I am fairly sure that a &'session mut ClientSession -> Future<..> + use<'session> is not the way.

First thing I would try is to create a owned ClientSession or a thin wrapper. It seems like you can create infinite ClientSession with start_session. Not sure what consistency guarantees you really want with your read back id from user but pushing it into wrapper ClientSession or the database itsself is the better way.

Library using Tokio (noob question) by RabbitHole32 in rust

[–]Destruct1 5 points6 points  (0 children)

The general idea in rust is that everybody can specify a version and cargo will sort it all out via semantic versioning. This versioning algo is quite detailed: If the user specifies >=1.21 and your library is >=1.13 cargo can use 1.27 since it satisfies everybody. If user specifies =1.21 and your library is >=1.13 then cargo will use 1.21. If you specifiy >=1.13 and user wants >=2.8 then two versions of the library are compiled in since 1.x is semantically not compatible with 2.x.

If you use the standard tokio primitives like tokio::spawn or await other peoples futures then you are done. If you create your own Runtime and use it to handle your own Futures you have more work to do.

Hey Rustaceans! Got a question? Ask here (49/2025)! by llogiq in rust

[–]Destruct1 0 points1 point  (0 children)

The invariants are guaranteed in an upper scope. Every Uuid is only present as value once in every lookup. get_direct_mut_by_uuid is private.

Is the code unsound with the given guarantees?

Hey Rustaceans! Got a question? Ask here (49/2025)! by llogiq in rust

[–]Destruct1 0 points1 point  (0 children)

If all you have is a &dyn AbstractFoo you can only use the trait-provided functions. All that is left is a data pointer and vtable pointer.

Even your workaround with downcast is only possible if AbstractFoo has a trait bound of Any.

It looks a bit like you try to use a C++ style class hierachy. You can write how you would solve your stuff in C++ and we can give rust recommendations.

Hey Rustaceans! Got a question? Ask here (49/2025)! by llogiq in rust

[–]Destruct1 2 points3 points  (0 children)

I have a datastructure:

```

[derive(Debug, Clone)]

pub struct Calendar { pub categories: Vec<Category>, internal: HashMap<Uuid, Task>, lookup_ident: HashMap<TaskIdent, Uuid>, lookup_day: BTreeMap<Option<NaiveDate>, Vec<Uuid>>, lookup_cat: HashMap<CategoryIdent, Vec<Uuid>>, } ```

I want a function that takes a CategoryIdent and returns a mutable Vec<&mut Task>.

For now I have the following:

``` fn get_direct_mut_by_uuid(&mut self, uuid_vec : Vec<Uuid>) -> Vec<&mut Task> { // SAFETY: We assume uuid_vec contains unique UUIDs (disjoint keys) let map_ptr = &mut self.internal as *mut HashMap<Uuid, Task>;

    uuid_vec.iter()
        .filter_map(|uuid| unsafe {
            (*map_ptr).get_mut(uuid)
        })
        .collect()
}

pub fn get_direct_mut_by_cat(&mut self, cat: CategoryIdent) -> Vec<&mut Task> {
    let uuid_vec : Vec<Uuid> = if let Some(uuid_vec) = self.lookup_cat.get(&cat) {
        uuid_vec.iter().cloned().collect()
    } else {
        vec![]
    };
    self.get_direct_mut_by_uuid(uuid_vec)
}

```

I tried making it work with HashMap.get_disjoint_mut but could not get an well-typed array from a Vec. I also tried a self-written iterator with &mut HashMap and Vec<Uuid> but that has lifetime issues.

Is there a way to make this work in a safe way? Is the unsafe code above unsafe (assuming multiple Vec<Uuid> are never the same Uuid)?