这是一种使用特征和泛型的方法:
#[derive(Debug)]
struct Color {
rgb: [u8; 3],
}
trait ColorType {
fn color(&self) -> &Color;
}
struct Player {
jump_power: f32,
color: Color,
size: (f32, f32),
pos: (f32, f32),
}
impl ColorType for Player {
fn color(&self) -> &Color {
&self.color
}
}
struct Pipe {
color: Color,
speed: f32,
size: (f32, f32),
pos: (f32, f32),
}
impl ColorType for Pipe {
fn color(&self) -> &Color {
&self.color
}
}
fn get_color<T: ColorType>(my_color_type: &T) -> &Color {
&my_color_type.color()
}
fn main() {
let pipe = Pipe {
color: Color { rgb: [255u8, 255u8, 255u8] },
speed: 0.0,
size: (0.0, 0.0),
pos: (0.0, 0.0),
};
let player = Player {
jump_power: 0.0,
color: Color { rgb: [255u8, 255u8, 255u8] },
size: (0.0, 0.0),
pos: (0.0, 0.0),
};
println!("Pipe color: {:#?}", get_color(&pipe));
println!("Player color: {:#?}", get_color(&player));
}
输出:
Pipe color: Color {
rgb: [
255,
255,
255,
],
}
Player color: Color {
rgb: [
255,
255,
255,
],
}
Rust Playground Link