3 ms·
One of the biggest struggles I have (and others have, judging from Stack Overflow) is how to generically handle accepting types of Box<T>, Rc<T>, T, Pin<T>, &T,
by andy_xor_andrew 2y ago
One of the biggest struggles I have (and others have, judging from Stack Overflow) is how to generically handle accepting types of Box<T>, Rc<T>, T, Pin<T>, &T, &mut T, etc etc.
Of course you can write a function that is generic on <I, T: AsRef<I>> or something, but the moment you introduce function-coloring stuff like async, object safety, etc, things explode.
- pylua 2y agoIs that by design ? I am a novice at rust, but that is sort of how it feels. I could be missing something.
- pornel 2y agoIt requires supporting higher-kinded types, and Rust was reluctant to add them (although it’s slowly getting there with higher kinded lifetimes and generic associated types).
- unstruktured 2y agomacros can help with this if you can narrow down the traits you want to support. https://doc.rust-lang.org/reference/macros.html https://doc.rust-lang.org/reference/macros.html
- 3836293648 2y agoYou just write an &T version and let everyone coerce their smart pointer into a reference on call? Worst case you write your generic asref function and then immediately delegate to the &T version
- deleted 2y ago[deleted]
- vishalontheline 2y agoIs there an ELI5 video / tutorial for all things box-variables that you can recommend? I understand pointers, I understand references, I understand ownership and mutability. I feel lost with Box things. The official documentation came across as cryptic to me and I had a hard time getting over the syntax. Like, what is "T" and why does it get passed into Box<> ... etc.
- mmastrac 2y agoI wrote https://github.com/mmastrac/keepcalm https://github.com/mmastrac/keepcalm as a way to help with this, especially for writing webserver-like code. For most cases this type of code can take a small perf hit in exchange for drastically simplifying the sharing of data in the system.
- wtetzner 2y agoYeah, I typically use `impl AsRef<T>`. It would be really nice to be able to say roughly the same thing, but have the `.as_ref()` call happen at the call site instead of within the function.