Rust newbie question about string replacement [duplicate] - rust

This question already has answers here:
Return local String as a slice (&str)
(7 answers)
Missing Lifetime Operator
(3 answers)
Closed 8 months ago.
fn get_filename_from_url(url: &str, extension: &str) -> str {
let dt = chrono::Local::now();
let cleaned_url = url
.replace("https://", "")
.replace("/", "-")
.replace("?", "-")
.as_str();
return format!(
"{}{}_{}{}",
OUTPUT_FOLDER,
cleaned_url,
dt.format("%Y-%m-%d_%H.%M.%S"),
extension
)
.as_str();
}
I get errors such as:
error[E0106]: missing lifetime specifier
--> src/scraper.rs:14:57
|
14 | fn get_filename_from_url(url: &str, extension: &str) -> &str {
| ---- ---- ^ expected named lifetime parameter
What am I doing wrong?
P.S. I was also interested to see Is there a safe / sanitised filename function in Rust but didn't see a helpful example.

Related

Return Vec<str> from function [duplicate]

This question already has answers here:
Return local String as a slice (&str)
(7 answers)
Proper way to return a new string in Rust
(2 answers)
What does “`str` does not have a constant size known at compile-time” mean, and what's the simplest way to fix it?
(1 answer)
What are the differences between Rust's `String` and `str`?
(14 answers)
Closed 1 year ago.
If I do
fn split(text: String) -> Vec<str> {
It tells me this
29 | fn split(text: String) -> Vec<str> {
| ^^^^^^^^ doesn't have a size known at compile-time
|
= help: the trait `Sized` is not implemented for `str`
100% not the best way to do this but I did this
fn split(text: String) -> Vec<String> {
let mut output_string:Vec<String> = Vec::new();
for x in output {
output_string.push(String::from(x));
}
return output_string;

concat string using format!() and return to &'static str [duplicate]

This question already has answers here:
Return local String as a slice (&str)
(7 answers)
How to concatenate static strings in Rust
(3 answers)
Closed 2 years ago.
This post was edited and submitted for review 10 months ago and failed to reopen the post:
Duplicate This question has been answered, is not unique, and doesn’t differentiate itself from another question.
I'll get error when compiled: 'returns value referencing data owned by the current function'
here's the code:
fn return_static_str(a: &'static str, b: &'static str) -> &'static str {
format!("{} {}", a,b).as_str()
}
fn main() {
let s = return_static_str("Hello ", "World!");
}
using return as_ref() get same issue.

Struct str attribute must be reference? [duplicate]

This question already has answers here:
How to solve "returns a value referencing data owned by the current function" error in Rust? [duplicate]
(1 answer)
Return local String as a slice (&str)
(7 answers)
Why can't I return an &str value generated from a String?
(1 answer)
Is there any way to return a reference to a variable created in a function?
(5 answers)
Closed 3 years ago.
For the following code:
fn get_lines() -> String {
String::from("Hello\nWorld")
}
fn get_first_line(s: &String) -> &str {
s.lines().next().unwrap()
}
struct World<'a> {
a_str: &'a str,
}
fn work<'a>() -> World<'a> {
let s1 = get_lines();
let s2 = get_first_line(&s1);
World { a_str: s2 }
}
fn main() {
let w = work();
}
I got the following error:
error[E0515]: cannot return value referencing local variable `s1`
--> src/main.rs:17:5
|
15 | let s2 = get_first_line(&s1);
| --- `s1` is borrowed here
16 |
17 | World { a_str: s2 }
| ^^^^^^^^^^^^^^^^^^^ returns a value referencing data owned by the current function
How to build a struct instance using s2? Is it a conceptual error of the World struct?
World refers to a str slice which must be owned by something else. Your function work allocates a new String (through get_lines), and makes a reference into it (through get_first_line). When it returns, the String goes out of scope and will be dropped, so you cannot keep a reference to it, since the thing it refers to is no longer there.
If you want a World object that does not depend on a String owned by something else, it will need to own the data itself: Contain a String instead of a &'a str.
See also 'dangling references' in the Rust Book.

Understanding lifetime of borrowed variables when stacking function calls [duplicate]

This question already has answers here:
How do I pass modified string parameters?
(2 answers)
Return local String as a slice (&str)
(7 answers)
Closed 4 years ago.
I can't seem to find anything about lifetimes for my specific situation. The search function has correct lifetimes and works fine, but then the search_case_insensitive function tells me the lifetime is too short, but I don't understand why.
pub fn search<'a>(query: &str, contents: &'a str) -> Vec<(&'a str, i32)> {
//do something
}
pub fn search_case_insensitive<'a>(query: &str, contents: &'a str) -> Vec<(&'a str, i32)> {
return search(&query.to_lowercase(), &contents.to_lowercase());
}
I get:
error[E0597]: borrowed value does not live long enough
--> src/lib.rs:44:43
|
44 | return search(&query.to_lowercase(), &contents.to_lowercase());
| ^^^^^^^^^^^^^^^^^^^^^^^ - temporary value only lives until here
| |
| temporary value does not live long enough
|
note: borrowed value must be valid for the lifetime 'a as defined on the function body at 43:1...
--> src/lib.rs:43:1
|
43 | pub fn search_case_insensitive<'a>(query: &str, contents: &'a str) -> Vec<(&'a str, i32)> {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
= note: consider using a `let` binding to increase its lifetime
I have tried doing things like let c = contents and using this new c value instead but get the same issue.

Convert format!() from String to &'static str [duplicate]

This question already has answers here:
How to convert a String into a &'static str
(4 answers)
Return local String as a slice (&str)
(7 answers)
Is it possible to return either a borrowed or owned type in Rust?
(1 answer)
Closed 5 years ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
I'm stumped on how to interpolate a number and return it in the correct format. I started with the function returning String but then the compiler wanted &'static str. I've read about to_owned but it's not clicking in my head yet. What is the "right" way to do what I'm attempting?
fn ordinal_name(num: i32) -> &'static str {
if num == 1 {
"1st"
} else if num == 2 {
"2nd"
} else if num == 3 {
"3rd"
} else {
format!("{}th", num)
}
}
fn main() {
println!("{}", ordinal_name(5));
}
error[E0308]: mismatched types
--> src/main.rs:9:9
|
1 | fn ordinal_name(num: i32) -> &'static str {
| ------------ expected `&'static str` because of return type
...
9 | format!("{}th", num)
| ^^^^^^^^^^^^^^^^^^^^ expected reference, found struct `std::string::String`
|
= note: expected type `&'static str`
found type `std::string::String`
= note: this error originates in a macro outside of the current crate
This is not a duplicate of String to &'static str - I'm trying to figure how to interpolate an integer with a string and then return a &static str.

Resources