面试题答案
一键面试// 定义泛型结构体Wrapper,关联生命周期参数 'a
struct Wrapper<'a, T> {
value: T,
}
// 为Wrapper结构体实现方法
impl<'a, T> Wrapper<'a, T> {
// 定义方法,接受相同生命周期的引用,并返回引用和成员变量的组合
fn combine(&self, other: &'a T) -> String
where
T: std::fmt::Display,
{
format!("{}{}", self.value.to_string(), other.to_string())
}
}
fn main() {
let wrapper = Wrapper {
value: "Hello, ".to_string(),
};
let other_str = "world!".to_string();
let result = wrapper.combine(&other_str);
println!("{}", result);
}