←back to thread

451 points birdculture | 3 comments | | HN request time: 0.586s | source
Show context
dmitrygr ◴[] No.43978986[source]
> Treat the borrow checker as a co-author, not an adversary

Why would I pair-program with someone who doesn’t understand doubly-linked lists?

replies(6): >>43979041 #>>43979123 #>>43979152 #>>43980150 #>>43980304 #>>43982624 #
1. pornel ◴[] No.43979152[source]
So that you learn that loaning is for giving temporary shared^exclusive access within a statically-known scope, and not for storing data.

Trying to construct permanent data structures using non-owning references is a very common novice mistake in Rust. It's similar to how users coming from GC languages may expect pointers to local variables to stay valid forever, even after leaving the scope/function.

Just like in C you need to know when malloc is necessary, in Rust you need to know when self-contained/owning types are necessary.

replies(2): >>43979733 #>>43982547 #
2. mplanchard ◴[] No.43979733[source]
The biggest thing I’ve run into where I really want self-referential types is for work that I want to perform once and then cache, while still needing access to the original data.

An example: parsing a cookie header to get cookie names and values.

In that case, I settled on storing indexes indicating the ranges of each key and value instead of string slices, but it’s obviously a bit more error prone and hard to read. Benchmarking showed this to be almost twice as fast as cloning the values out into owned strings, so it was worth it, given it is in a hot path.

I do wish it were easier though. I know there are ways around this with Pin, but it’s very confusing IMO, and still you have to work with pointers rather than just having a &str.

3. pjmlp ◴[] No.43982547[source]
Note that some users of GC languages that support stack allocation, are used that it is a compiler error trying to have such a pointer/reference.

D example, https://godbolt.org/z/bbfbeb19a

> Error: returning `& my_value` escapes a reference to local variable `my_value`

C# example, https://godbolt.org/z/Y8MfYMMrT

> error CS8168: Cannot return local 'num' by reference because it is not a ref local