我正在尝试将一对字符串引用列表转换为Attributes。它适用于&str
或&str
,后跟&String
(Deref
编辑为& 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);
}