Skip to content

Rust wisdom

Thang Chung edited this page Jul 8, 2021 · 9 revisions

Macros

Error management

Conventions

https://rust-lang.github.io/api-guidelines/naming.html#ad-hoc-conversions-follow-as_-to_-into_-conventions-c-conv

unwrap vs expect

Rust doesn't have function overloading, so there should be a way to declare "unwrap with a message", and that is expected.

expect == unwrap with a message

expect_err == unwrap_err with a message

About usage scenarios of "unwrap vs expect" Rust Book (Ch 9) says: "Using expect instead of unwrap and providing good error messages can convey your intent and make tracking down the source of a panic easier. Because this error message starts with the text we specified... it will be easier to find where in the code this error message is coming from."

into_inner

into_inner() is simply (by convention) a method that consumes self and returns an inner, “wrapped” object. In this case, the BufWriter wraps the stdout. It moves it into itself in new, so here (as is often the case) into_inner is kind of the "reverse of new".

In general, Rust methods are named "into_something when they consume self", avoiding clones as much as possible, and "to_something when they take &self", potentially cloning some data.

as_ vs to_ vs into_

  • as_ Free
    • borrowed -> borrowed-
  • to_ Expensive
    • borrowed -> borrowed
    • borrowed -> owned (non-Copy types)
    • owned -> owned (Copy types)
  • into_ Variable
    • owned -> owned (non-Copy types)

Ref at https://rust-lang.github.io/api-guidelines/naming.html#ad-hoc-conversions-follow-as_-to_-into_-conventions-c-conv

Clone this wiki locally