Why should I use SendStr (over & str or String) for the message property in the error structure in Rust?

I found this great blog post about error handling in Rust.

It defines the error structure as such:

struct ProgramError {
    kind: ProgramErrorKind,
    message: SendStr
}

      

The message uses SendStr

which is a type alias for MaybeOwned<'static>

. I understand it may contain either &str

or String

, but the documentation is a bit vague about its use.

This can be useful as an optimization when allocation is sometimes required but not always.

I would like to understand why you would like to choose SendStr

over &str

or String

in the case of class definition ProgramError

.

+3


source to share


1 answer


SendStr

- this String

or &'static str

, which allows you to work efficiently in the general case using a string literal (no need to allocate a new value every time), being able to use a dynamic if value is necessary.



Why not use it &str

all the time? Well, either you will need to make only static strings, or the user will need to store the string somewhere else in the case of dynamic values, and therefore passing the error around (primarily up the stack) will be more difficult.

+4


source







All Articles