我正试图构建一种HTTP web服务器作为一种学习练习,但在尝试使用for循环(通过实现
IntoIterator
)。
目前为止
我创建了一个数据结构
Response
对象(旨在为HTTP响应建模),并且该对象包含
Headers
对象(用于对HTTP响应标头进行建模),其中包含
HashMap<String, String>
,表示实际标头值:
use std::collections::HashMap;
struct Headers {
headers: HashMap<String, String>,
}
impl Headers {
pub fn new(headers: HashMap<String, String>) -> Self {
Self { headers }
}
}
struct Response {
headers: Headers,
}
impl Response {
pub fn new(headers: Headers) -> Self {
Self { headers }
}
pub fn headers(&self) -> &Headers {
&self.headers
}
}
注:
headers
方法返回一个不可变的引用,因为我只想读取这些值。理想情况下,我不想复制/克隆标题,只是为了让它们可以被读取。
目标
我想做的事情是这样的:
fn main() {
// just creating an example here
let mut headers = HashMap::new();
headers.insert("foo".to_string(), "one".to_string());
headers.insert("bar".to_string(), "two".to_string());
let response = Response::new(Headers::new(headers));
// this is what I'm aiming for:
for (key, value) in response.headers() {
println!("{}: {}", key, value);
}
}
我尝试过的
我已经尝试了很多方法来实现这一点,但到目前为止我都失败了。到目前为止,我最接近的是实现
IntoTerator
对于
&Headers
然后打电话
into_iter()
在哈希图上:
impl IntoIterator for &Headers {
type Item = (String, String);
type IntoIter = IntoIter<String, String>;
fn into_iter(self) -> Self::IntoIter {
self.headers.into_iter()
}
}
但是,这会导致一个错误:
无法搬出
self.headers
位于共享引用后面
我试着四处搜索,发现了许多类似的StackOverflow问题,但似乎没有一个能回答我的确切问题。
谢谢