4

我正在研究 Iron 的源代码Response::with(),试图了解它如何将元组作为修饰符应用于响应。

据我了解,修饰符只是一个构建器对象,它接受对当前上下文 ( self) 的引用并将您希望构建的对象作为参数(只要您实现该modify函数)。

假设我们有以下代码:

use iron::modifiers::Header;

fn hello_world(_: &mut Request) -> IronResult<Response> {
    let string = get_file_as_string("./public/index.html");
    let content_type = Header(ContentType(Mime(TopLevel::Text, SubLevel::Html, vec![])));
    Ok(Response::with((status::Ok, string, content_type)))
}

通过文档挖掘,我可以看到Response::with()Iron 的实现如下:

pub fn new() -> Response {
    Response {
        status: None, // Start with no response code.
        body: None, // Start with no body.
        headers: Headers::new(),
        extensions: TypeMap::new()
    }
}

/// Construct a Response with the specified modifier pre-applied.
pub fn with<M: Modifier<Response>>(m: M) -> Response {
    Response::new().set(m)
}

我正在努力查看我的对象元组是如何转换为修饰符的?我希望看到一个 foreach 可能迭代每个修饰符,但在这里我只看到一个 set 操作。

有人可以在这里解释执行顺序并揭示实际发生的情况吗?

4

1 回答 1

5

有趣的问题!我们再来看看函数签名:

fn with<M: Modifier<Response>>(m: M) -> Response

这意味着with只接受一个实现Modifier<Response>. 所以接下来我们可以查看哪些类型实现了 trait Modifier。在文档中,我们看到它不仅适用于Stringor Status,而且适用于元组类型!这些实现都写在这个文件中。例如,让我们看一下这个 impl:

impl<X, M1, M2, M3> Modifier<X> for (M1, M2, M3)
    where M1: Modifier<X>,
          M2: Modifier<X>,
          M3: Modifier<X> 
{
    fn modify(self, x: &mut X) {
        self.0.modify(x);
        self.1.modify(x);
        self.2.modify(x);
    }
}

这实现了每个元素也实现的大小为 3 的元组的特征Modifier。而实现modify就是调用modify每个元组元素的-implementation;这是您正在寻找的foreach 。

于 2016-05-24T12:27:01.057 回答