无法跟踪 Rust 中的类型期望错误

Unable to trace type-expectation error in Rust

存储库
https://github.com/hunterlester/rusty_arcade

版本
生锈:1.7.0
sdl2: 0.16.1
sdl2_image: 0.16.0

错误

src/views/mod.rs:88:13: 93:23 error: mismatched types:
 expected `core::option::Option<sdl2::rect::Rect>`,
    found `sdl2::rect::Rect`
(expected enum `core::option::Option`,
    found struct `sdl2::rect::Rect`) [E0308]
src/views/mod.rs:88             Rectangle {
src/views/mod.rs:89                 x: 0.0,
src/views/mod.rs:90                 y: 0.0,
src/views/mod.rs:91                 w: self.player.rect.w,
src/views/mod.rs:92                 h: self.player.rect.h,
src/views/mod.rs:93             }.to_sdl(),
src/views/mod.rs:88:13: 93:23 help: run `rustc --explain E0308` to see  a detailed explanation
src/views/mod.rs:94:13: 94:38 error: mismatched types:
 expected `core::option::Option<sdl2::rect::Rect>`,
    found `sdl2::rect::Rect`
(expected enum `core::option::Option`,
    found struct `sdl2::rect::Rect`) [E0308]
src/views/mod.rs:94             self.player.rect.to_sdl()

追踪它
指定文件的第93行和第94行。

phi.renderer.copy(&mut self.player.tex,
            Rectangle {
                x: 0.0,
                y: 0.0,
                w: self.player.rect.w,
                h: self.player.rect.h,
            }.to_sdl(), // Line 93
            self.player.rect.to_sdl() // Line 94
        );

我假设这与 .to_sdl() 方法返回的内容有关。

to_sdl方法

impl Rectangle {
    pub fn to_sdl(self) -> SdlRect {
        assert!(self.w >= 0.0 && self.h >= 0.0);

        SdlRect::new(self.x as i32, self.y as i32, self.w as u32,  self.h as u32)
    }

to_sdl returns 在文件顶部使用的 SdlRect:

use sdl2::rect::Rect as SdlRect;

sdl2 来源
https://github.com/AngryLawyer/rust-sdl2/blob/master/src/sdl2/rect.rs

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Rect {
    raw: ll::SDL_Rect,
}

impl Rect {

pub fn new(x: i32, y: i32, width: u32, height: u32) -> Rect {
    let raw = ll::SDL_Rect {
        x: clamp_position(x),
        y: clamp_position(y),
        w: clamp_size(width) as i32,
        h: clamp_size(height) as i32,
    };
    Rect { raw: raw }
}

我看不到 sdl2::rect::Rect 应该在 core::option::Option 枚举类型中的什么地方。

如果您碰巧熟悉我正在学习的教程,您会注意到我使用的 sdl2_image 版本与教程中指定的版本不同,因为指定版本已从板条箱。

sdl2_image 取决于 sdl2 的不同版本,我必须匹配它以处理其他错误。

错误意味着表达式 self.player.rect.to_sdl() 产生了一个 SdlRect,但是无论使用那个值,都期望得到一个 Option<SdlRect>。您正在调用 sdl2::render::Renderercopy,它具有以下参数:

&mut self, texture: &Texture, src: Option<Rect>, dst: Option<Rect>

如你所见,你需要传递两个Option<Rect>。 sdl-crate 的文档甚至说明了原因:

Copies a portion of the texture to the current rendering target.

  • If src is None, the entire texture is copied.
  • If dst is None, the texture will be stretched to fill the given rectangle.