面试题答案
一键面试在Rust中,可以使用泛型和Trait约束来实现这个函数。以下是示例代码:
trait Addable {
type Output;
fn add(self, other: Self) -> Self::Output;
}
struct A(i32);
struct B(f32);
impl Addable for A {
type Output = A;
fn add(self, other: A) -> A {
A(self.0 + other.0)
}
}
impl Addable for B {
type Output = B;
fn add(self, other: B) -> B {
B(self.0 + other.0)
}
}
fn add<T: Addable>(a: T, b: T) -> T::Output {
a.add(b)
}
在上述代码中:
- 定义了一个
trait Addable
,它要求实现类型定义Output
类型,并实现add
方法。 - 分别为
A
和B
结构体实现了Addable
trait。 - 定义了一个泛型函数
add
,它接收两个实现了Addable
trait的参数,并返回它们相加的结果。
如果要考虑类型转换,可以在实现Addable
trait的add
方法中进行处理。例如,假设要实现A
和B
之间的加法,可以这样做:
trait Addable {
type Output;
fn add(self, other: Self) -> Self::Output;
}
struct A(i32);
struct B(f32);
impl Addable for A {
type Output = A;
fn add(self, other: A) -> A {
A(self.0 + other.0)
}
}
impl Addable for B {
type Output = B;
fn add(self, other: B) -> B {
B(self.0 + other.0)
}
}
impl Addable for A {
type Output = B;
fn add(self, other: B) -> B {
B(self.0 as f32 + other.0)
}
}
impl Addable for B {
type Output = B;
fn add(self, other: A) -> B {
B(self.0 + other.0 as f32)
}
}
fn add<T: Addable, U: Addable<Output = T::Output>>(a: T, b: U) -> T::Output {
a.add(b)
}
在上述更新的代码中,分别为A
和B
实现了相互之间的加法,并更新了add
函数的泛型参数,使得它能处理不同类型但满足Addable
关系的参数。