如何在通道上发送内插字符串?
How do I send an interpolated string on a channel?
如何在字符串中存储变量?我已经阅读了示例,但它们都只是 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);
我正在使用 tx.send()
并且想像这样在频道上发送一个内插字符串:
let url_str = "http://api.weather";
c.send(url_str);
但是我得到一个错误
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);
^~~~~~~
这是我为构建 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);
}
随着被删除的生命周期和类型的恢复,这就是你所拥有的:
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);
}
请记住String
和&str
之间的区别:&str
是一个字符串切片,是对其他人拥有的字符串的引用; String
是自有品种。
'b
必须至少与整个函数体一样长——您在函数内部构造的任何字符串都不会存在 'b
。因此,您的发件人需要发送 String
,而不是 &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);
}
如何在字符串中存储变量?我已经阅读了示例,但它们都只是 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);
我正在使用 tx.send()
并且想像这样在频道上发送一个内插字符串:
let url_str = "http://api.weather";
c.send(url_str);
但是我得到一个错误
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);
^~~~~~~
这是我为构建 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);
}
随着被删除的生命周期和类型的恢复,这就是你所拥有的:
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);
}
请记住String
和&str
之间的区别:&str
是一个字符串切片,是对其他人拥有的字符串的引用; String
是自有品种。
'b
必须至少与整个函数体一样长——您在函数内部构造的任何字符串都不会存在 'b
。因此,您的发件人需要发送 String
,而不是 &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);
}