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?

0

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

why let Err 's message lives as long as the program lives
@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.
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.
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

1 Comment

this is also one of my confusion, why the code need 'static str live as long as program running?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.