1

I've come across a piece of code that returns Err("some errors") with a return type of Result<T, &'static str>. This confuses me.

Why does it use 'static str? I know that static means a "spacial" pace in memory.

pub fn push(&self, node: Rc<RefCell<Node<T>>>) -> Result<(), &'static str> {
   ...
   Err("some errors")
   ...
}

Is there some other case where 'static str is useful?

En Xie
  • 510
  • 4
  • 19

2 Answers2

1

There is nothing special about Err. In a real program, you probably wouldn't want to use string literals (&'static str) for errors, but either something general, like Box<dyn std::error::Error>, a concrete one, like std::io::Error.

However, one of the most popular approaches is the anyhow crate.

Riwen
  • 4,734
  • 2
  • 19
  • 31
  • why let Err 's message lives as long as the program lives – En Xie Dec 17 '21 at 15:57
  • 1
    @EnXie that's how string literals work - they are "baked into" the executable. Alternative of returning a `String` means that every time you want to return an `Err` variant, you have to allocate the `String`, then that string has to be freed at some point. So it's probably more overhead than just returning a reference to the single instance of `str` in the static memory every time. – justinas Dec 17 '21 at 15:59
  • Especially since you need to have the text somewhere in your program. So if you use a `String` (e.g. with `"message".to_string()`), you still have a `&'static str` anyway (the `"message"` literal) even if you convert it to a `String` immediately. – Jmb Dec 18 '21 at 09:01
0

'static is a reserved name for a lifetime in Rust. It is used to indicate that the data pointed to by the reference lives for the entire lifetime of the running program. In terms where it located, it will be in the read only memory of the binary.

As to why &str is typically preferred over String in this case - String is a growable, heap-allocated data structure whereas str is an immutable fixed-length string somewhere in memory.

In this case - using a &str for the error message type makes sense, as it is effectively a read-only view into a string, and allowing an error message to be mutated directly is most likely not desired

syllabix
  • 2,240
  • 17
  • 16
  • this is also one of my confusion, why the code need 'static str live as long as program running? – En Xie Dec 17 '21 at 15:36