【问题标题】:Polymorphism alternatives in rustrust 中的多态性替代方案
【发布时间】:2022-11-01 12:58:45
【问题描述】:

我有 2 个非常相似的结构,我想问一下 rust 中的 java/kotlin 中是否有类似的多态性?

struct Player {
    jump_power: f32,
    color: Color,

    size: (f32, f32),
    pos: (f32, f32),
}

struct Pipe {
    color: Color,
    speed: f32,

    size: (f32, f32),
    pos: (f32, f32),
}

我不确定我应该从哪里开始。

【问题讨论】:

  • rust 中没有结构继承。你可以试试作品(将相同的值提取到另一个结构中,并将这种新类型的字段放入其他结构中)。
  • 首先确定您要解决的确切问题。

标签: rust struct


【解决方案1】:

Rust 通常需要一种不同的方法来更巧妙地适应 Rust 的功能。如果你想要一个可以是PipePlayer 的东西,那么你可能想要一个enum

enum Actor {
  Player(Player),
  Pipe(Pipe)
}

现在Actor 可以是其中之一。

如果你有像color 这样的共同属性,你甚至可以这样做:

impl Actor {
    pub fn color(&self) -> Color {
        match self {
            Self::Player(p) => p.color,
            Self::Pipe(p) => p.color
        }
    }
}

通常你会想要impl From<Player> for Actor 作为构建这些的方便,但这不是唯一的方法。

【讨论】:

    【解决方案2】:

    这是一种使用特征和泛型的方法:

    #[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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-28
      • 1970-01-01
      • 1970-01-01
      • 2011-05-24
      • 1970-01-01
      相关资源
      最近更新 更多