Auto Coerce& String to& str

时间:2018-02-25 04:40:12

标签: rust

我正在尝试将一对字符串引用列表转换为Attributes。它适用于&str&str,后跟&StringDeref编辑为& str)或String.as_ref()。但是当第一个参数的类型为&String时,编译器会出错:

the trait std::convert::AsRef<[(&'static str, &str)]> is not implemented for [(&str, &std::string::String); 1]

如何允许&String强迫&str作为第一个参数?

use std::collections::HashMap;

#[derive(Debug)]
pub struct Attributes<'a>(HashMap<&'static str, &'a str>);

impl<'a, T> From<T> for Attributes<'a>
where
    T: AsRef<[(&'static str, &'a str)]>,
{
    fn from(item: T) -> Self {
        Attributes(item.as_ref().into_iter().map(|&(k, v)| (k, v)).collect())
    }
}

fn main() {
    let fruit = "banana".to_string();
    let attr: Attributes = [("fruit", "apple"), ("new_fruit", &fruit)].into(); // This works. As it is coerced into &str because of the first one.
    let another: Attributes = [("fruit", &fruit)].into(); // Does not work as type is &String. Help! Make it work.
    let one_more: Attributes = [("fruit", fruit.as_ref())].into(); // Works
    println!("{:?}", attr);
    println!("{:?}", another);
    println!("{:?}", one_more);
}

Link to Rust Playground

0 个答案:

没有答案