Rust 如何实现用于Hyper的自定义类型标头?

Rust 如何实现用于Hyper的自定义类型标头?,rust,hyper,Rust,Hyper,我更愿意利用Hyper方法的类型安全性,而不是使用&str 实现这一点的最佳方法是什么?在hyper::header::Headers源代码中,我发现有一个整洁的宏用于生成代码:。不过,您需要一些咒语才能使其有用: #[macro_use] extern crate hyper; use hyper::{Body, Method, Request, Response}; use std::fmt::{self, Display}; use std::str::FromStr; use std:

我更愿意利用Hyper方法的类型安全性,而不是使用
&str


实现这一点的最佳方法是什么?

hyper::header::Headers
源代码中,我发现有一个整洁的宏用于生成代码:。不过,您需要一些咒语才能使其有用:

#[macro_use]
extern crate hyper;

use hyper::{Body, Method, Request, Response};
use std::fmt::{self, Display};
use std::str::FromStr;
use std::num::ParseIntError;

// For a header that looks like this:
//    x-arbitrary-header-with-an-integer: 8

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ArbitraryNumber(i8);

impl Display for ArbitraryNumber {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Arbitrary Protocol v{}", self.0)
    }
}

impl FromStr for ArbitraryNumber {
    type Err = ParseIntError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        s.parse::<i8>().map(|int| ArbitraryNumber(int))
    }
}

//impl Header for ArbitraryNumberHeader
header! { (ArbitraryNumberHeader, "x-arbitrary-header-with-an-integer") => [ArbitraryNumber] }
let arbitrary_header: AribitraryNumber = res.headers().get::<ArbitraryNumberHeader>().unwrap();