Rust返回结构体时的所有权问题:SDL2游戏开发报错求助
解决Rust SDL2中Window所有权移动的问题
问题根源
你遇到的错误核心是:Window::into_canvas()方法会转移Window实例的所有权来创建WindowCanvas,调用这个方法后,原window变量就不能再被使用了,但你还试图将它放入Screen结构体,这违反了Rust的所有权规则。同时你的Screen结构体不需要同时存储window和canvas——因为WindowCanvas本身已经持有Window的所有权,完全可以通过它访问Window的相关功能。
修复方案
- 移除Screen结构体中的
window字段 - 调整new方法,不再尝试将已移动的window存入结构体
修改后的代码如下:
pub struct Screen { sdl_context: Sdl, video_subsystem: VideoSubsystem, event_pump: EventPump, canvas: WindowCanvas, // 无需用Option,new方法中已确保创建成功 pub width: u32, pub height: u32 } impl Screen { pub fn new(width: u32, height: u32, title: &str) -> Self { let sdl_context = sdl2::init().unwrap(); let video_subsystem = sdl_context.video().unwrap(); let window = WindowBuilder::new(&video_subsystem, title, width, height) .position_centered() .build() .unwrap(); // 调用into_canvas后,window的所有权转移给了canvas let canvas = window.into_canvas().accelerated().build().unwrap(); let event_pump = sdl_context.event_pump().unwrap(); Screen { sdl_context, video_subsystem, event_pump, canvas, width, height, } } // 如果需要访问Window的功能,添加方法返回引用即可 pub fn window(&self) -> &Window { self.canvas.window() } }
补充说明
- 如果你之前用
Option<WindowCanvas>是为了处理创建失败的情况,可以把new方法的返回值改成Result<Self, String>,将unwrap()替换为?实现容错。 - 其他变量(如Sdl、VideoSubsystem)的所有权处理是正确的,它们会被正常转移到Screen结构体中,不会出现生命周期问题。
内容的提问来源于stack exchange,提问作者user16835604
相关产品推荐
相关产品推荐

