gpt4 book ai didi

rust - 如何关闭宏观卫生?

转载 作者:行者123 更新时间:2023-12-03 11:45:01 26 4
gpt4 key购买 nike

我正在尝试制作一个粘贴在样板代码中的宏,我想使用此后粘贴的变量。 Rust的宏观卫生状况正在阻止这种情况;如何关闭此功能?
我知道可以通过将所有变量传递到宏中来解决该问题,但这会使宏无用……我发现了一个名为不卫生的 crate ,它说的确实如此,但我无法它的工作。
这就是它应该如何工作的。这是您可以在Java或JavaScript中使用“处理”(图形/图形框架)的方式(这将显示正在移动的汽车(在Car类中定义)和一个矩形):

// You need to add a library or use the pde to be able to make this work though

let car;

setup() {
createCanvas(500, 100);
frameRate(60);
car = new Car();
}

draw() {
car.move();
car.show();

// this draws a rectangle at a certain place
rect(100, 200, 200, 100)
}
setup是在主循环之前执行的所有操作,而 draw是在循环内执行的所有操作。这就是我想要在Rust中使用它的方式(绝对不需要,仅出于美观目的):
//does all the boilerplate opengl setup. 
setup!{
// setting my variables and settings
}

// // adds a loop around the code in it and keeps up the framerate etc
draw!{
// do my updating and drawing commands
}

最佳答案

尝试使用特征!这显示了如何实现此功能的一般概述:
Playground

// Library:
mod library {
pub trait Program {
fn setup(ctx: &mut Context) -> Self;
fn draw(&mut self, ctx: &mut Context);
}

pub struct Context;

impl Context {
pub fn create_canvas(&mut self, width: usize, height: usize) {
// ...
}

pub fn frame_rate(&mut self, fps: usize) {
// ...
}

pub fn rect(&mut self, x: usize, y: usize, w: usize, h: usize) {
// ...
}
}

pub fn run_program<P: Program>() {
let ctx = Context;
let program = P::setup(&mut ctx);

loop {
program.draw(&mut ctx);
}
}
}

// User:
use library::{Context, Program};

struct Car;

impl Car {
// `move` is a reserved keyword
fn move_pos(&mut self, ctx: &mut Context) {
// ...
}

fn show(&mut self, ctx: &mut Context) {
// ...
}
}

struct MyProgram {
car: Car,
}

impl Program for MyProgram {
fn setup(ctx: &mut Context) -> Self {
ctx.create_canvas(500, 100);
ctx.frame_rate(60);

Self { car: Car }
}

fn draw(&mut self, ctx: &mut Context) {
self.car.move_pos(ctx);
self.car.show(ctx);

// this draws a rectangle at a certain place
ctx.rect(100, 200, 200, 100)
}
}

fn main() {
library::run_program::<MyProgram>();
}
我知道在各处传递 ctx有点麻烦,但这是值得的,因为您不必担心使用 Rc<RefCell<...>>(使用多个线程会变得更加复杂)来确保对a的唯一访问通过缓慢的,运行时检查过的内存管理共享上下文。您可以同时运行多个程序,每个程序都有其自己的上下文,并且您知道在任何给定时间,最多有一个函数正在写入上下文。

关于rust - 如何关闭宏观卫生?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63382149/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com