Reputation: 2164
How do I store a variable in a string? I've read the examples, but they are all just println!()
.
//javascript
var url_str = "http://api.weather/city" + city_code + "/get";
//go
urlStr := fmt.Sprintf("http://api.weather/%s/get", cityCode)
// Edit: Rust
let url_str = format!("http://api.openweathermap.org/data/2.5/weather?q={}", city_code);
I am using tx.send()
and want to send an interpolated string on the channel like this:
let url_str = "http://api.weather";
c.send(url_str);
but I get an error
src/http_get/http_getter.rs:21:17: 21:24 error: `url_str` does not live long enough
src/http_get/http_getter.rs:21 c.send(&url_str);
^~~~~~~
Here is the function that I am trying to implement for constructing the URL:
pub fn construct_url(c: &Sender<String>, city_code: &str) {
let url_str = format!("http://api.openweathermap.org/data/2.5/weather?q={}", city_code);
println!("{}", url_str);
c.send(url_str);
}
Upvotes: 2
Views: 756
Reputation: 90852
With elided lifetimes and types reinstated, here’s what you have:
pub fn construct_url<'a, 'b, 'c>(c: &'a Sender<&'b str>, city_code: &'c str) {
let url_str: String = format!("http://api.openweathermap.org/data/2.5/weather?q={}", city_code);
println!("{}", url_str);
c.send(&url_str);
}
Bear in mind the distinctions between String
and &str
: &str
is a string slice, a reference to a string that someone else owns; String
is the owned variety.
'b
is necessarily at least as long as the entire function body—any string you construct inside the function will not live long enough for 'b
. Therefore your sender will need to send a String
, not a &str
.
pub fn construct_url(c: &Sender<String>, city_code: &str) {
let url_str = format!("http://api.openweathermap.org/data/2.5/weather?q={}", city_code);
println!("{}", url_str);
c.send(url_str);
}
Upvotes: 4