this post was submitted on 26 Jul 2023
42 points (97.7% liked)

Rust Programming

8189 readers
5 users here now

founded 5 years ago
MODERATORS
 

Whenever I encounter an interesting Rust programming technique, I add it to this blog post. I've amassed a bit of a collection. Hopefully someone finds it interesting and useful!

top 7 comments
sorted by: hot top controversial new old
[–] [email protected] 4 points 1 year ago

These are actually nice, thanks!

[–] [email protected] 2 points 1 year ago (1 children)

In tip #3 I don't see any benefit of doing impl AsRef<[T]> over &[T]

[–] [email protected] 1 points 1 year ago (1 children)

@calcopiritus @hatchet That way you can pass a reference or anything that can be turned into a reference as an argument. So the caller can supply a &T, Box, Rc, Arc, … (I dont’t know if there is a blanket impl so that even T itself will work.

[–] hatchet 1 points 1 year ago (1 children)

Well, actually I would tend to agree that &[T] is preferable to AsRef in most cases; all of the smart pointers you mentioned can also easily be turned into plain references. I probably could have chosen a better example.

[–] [email protected] 1 points 1 year ago

@hatchet That is true and I mostly agree with you. AsRef makes function signatures more complex and you effectively change a simple function into a generic function.

That said, when using some crates that make heavy use of this construction (especially when working with owned values in call chains) is sometimes significantly more ergonomic.

So AsRef definitely had it’s uses, but I agree that it probably shouldn’t be the recommended “best practice” for all crates.

[–] [email protected] 1 points 1 year ago

Bookmarked :)

[–] [email protected] 0 points 1 year ago* (last edited 1 year ago)

Nice job! I’d add that the target of the Rustdoc link shortcuts can be customized, in case they are not autodetected or point to an undesired location, like so:

/// Use a [Tool]
///
/// [Tool]: lib::types::Tool

That will make the word Tool point to that type (note that the namespaces there - in lib::types::Tool - are relative to the current module / context, so you can use an imported name directly there too, for example).

load more comments
view more: next ›