static_str/
lib.rs

1//!
2//! convert a string into a static str
3//! and string to &str
4//! 
5//! fix cannot return reference to temporary value
6//! ```rust
7//! fn string_to_static_str_works() {
8//!     let option_value = Some(123);
9//!     // cannot return reference to temporary value
10//!     // let v = option_value.map_or("", |v| v.to_string().as_str());
11//!     let v = option_value.map_or("", |v| to_str(v.to_string()));
12//!     assert_eq!(v, "123");
13//! }
14//! ```
15
16pub fn string_to_static_str(s: String) -> &'static str {
17    Box::leak(s.into_boxed_str())
18}
19
20pub fn to_str(s: String) -> &'static str {
21    string_to_static_str(s)
22}
23
24mod tests {
25
26    use super::*;
27
28    #[test]
29    fn string_to_static_str_works() {
30        let option_value = Some(123);
31        let v = option_value.map_or("", |v| to_str(v.to_string()));
32        assert_eq!(v, "123");
33    }
34}