I found this excellent blog post about error handling in Rust.
It defines an error struct as such:
struct ProgramError {
kind: ProgramErrorKind,
message: SendStr
}
For the message it uses SendStr
which is an type alias for MaybeOwned<'static>
. I understand that this can either hold an &str
or an String
but the documentation is a bit vague about its use case.
This can be useful as an optimization when an allocation is sometimes needed but not always.
I would like to understand why one would like to choose SendStr
over &str
or String
in the case of defining a ProgramError
class.
SendStr
is String
or &'static str
, allowing it to be efficient in a common case of using a string literal (no need to allocate a new value each time), while being able to use a dynamic value if necessary.
Why not use &str
all the time? Well, either you'll need to make it static strings only, or the user will need to store the string somewhere else in the case of dynamic values, and so passing an error around (most notably, up the stack) will be more difficult.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.