简体   繁体   English

如何在 rust 特征中声明这样的 function

[英]How can I declare a function like this in rust trait

for example.例如。 need a global object and determine the object at runtime需要一个全局 object 并在运行时确定 object

class A{
};

A* a = nullptr;


// B inherit from A
void Import(B* b){
    a = b;
}

I have tried using the Dyn but must Determine the type我尝试过使用 Dyn 但必须确定类型

static mut instance: &dyn plugin::BasePlugin;
                                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^help: provide a definition for the static: `= <expr>;`

You should not use static mut .您不应使用static mut It's an unsafe-by-design construct meant for low-level code, not normal users who just want a global variable.这是一个不安全的设计结构,适用于低级代码,而不是只需要全局变量的普通用户。

Rust assumes single-threaded programs don't exist, so every global variable must be thread-safe. Rust 假定不存在单线程程序,因此每个全局变量都必须是线程安全的。 Therefore, to mutate it you will have to use a Mutex or some other thread-safety alternative like ArcSwap .因此,要对其进行变异,您将不得不使用Mutex或其他一些线程安全替代方案,例如ArcSwap You will need lazy_static to initialize these types.您将需要lazy_static来初始化这些类型。

You won't be able to use just any temporary scope-limited reference in a global variable.您将无法在全局变量中仅使用任何临时范围受限的引用。 & is not a general-purpose way to refer to objects in Rust. &不是引用 Rust 中对象的通用方式。 Consider using Box<dyn BasePlugin> or Arc<dyn BasePlugin> instead.考虑改用Box<dyn BasePlugin>Arc<dyn BasePlugin> These allow holding objects by reference without scoped lifetime limitations.这些允许通过引用保存对象,而没有范围生命周期限制。

You could use a &'static reference, but in practice that would require leaking heap memory.您可以使用&'static引用,但实际上这需要泄漏堆 memory。 If you plan to set the variable once, it would be okay.如果您打算设置一次变量,那就没问题了。 If you plan to set it more than once, that's not elegant, and may become problematic.如果您打算多次设置它,那并不优雅,并且可能会出现问题。

And finally, consider not using global variables at all.最后,考虑完全不使用全局变量。 Create objects you need stored in local variables (even as early as in main() ), and pass them down as arguments to functions that need them.创建您需要存储在局部变量中的对象(甚至早在main()中),并将它们作为 arguments 传递给需要它们的函数。 You could make a struct App and put data you need as fields of that struct.您可以制作一个struct App并将您需要的数据作为该结构的字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM