在系统中只创建一个实例的结构创建和使用的最佳方法是什么?是的,这是必要的,它是OpenGL子系统,制作多个副本并将其传递到各处会增加混乱,而不是减轻它.
单身人士需要尽可能高效.似乎不可能在静态区域上存储任意对象,因为它包含Vec带有析构函数的对象.第二个选项是在静态区域存储(不安全)指针,指向堆分配单例.什么是最方便和最安全的方法,同时保持语法简洁.
这是一个有争议的话题,所以让我先解释一下我的用例,然后再谈谈实际问题.
我发现对于一堆不安全的东西,确保你不泄漏记忆是很重要的; 如果你开始使用transmute()和,这实际上很容易做到forget().例如,将盒装实例传递给C代码一段任意时间,然后将其取回并使用"恢复它" transmute.
想象一下,我有这种API的安全包装:
trait Foo {}
struct CBox;
impl CBox {
/// Stores value in a bound C api, forget(value)
fn set<T: Foo>(value: T) {
// ...
}
/// Periodically call this and maybe get a callback invoked
fn poll(_: Box<Fn<(EventType, Foo), ()> + Send>) {
// ...
}
}
impl Drop for CBox {
fn drop(&mut self) {
// Safely load all saved Foo's here and discard them, preventing memory leaks
} …Run Code Online (Sandbox Code Playgroud) 我目前正在Rust(1.0)的生命中挣扎,特别是在通过通道传递结构时.
我将如何编译这个简单的例子:
use std::sync::mpsc::{Receiver, Sender};
use std::sync::mpsc;
use std::thread::spawn;
use std::io;
use std::io::prelude::*;
struct Message<'a> {
text: &'a str,
}
fn main() {
let (tx, rx): (Sender<Message>, Receiver<Message>) = mpsc::channel();
let _handle_receive = spawn(move || {
for message in rx.iter() {
println!("{}", message.text);
}
});
let stdin = io::stdin();
for line in stdin.lock().lines() {
let message = Message {
text: &line.unwrap()[..],
};
tx.send(message).unwrap();
}
}
Run Code Online (Sandbox Code Playgroud)
我明白了:
error[E0597]: borrowed value does not live long enough
--> src/main.rs:23:20
|
23 | text: …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用创建的结构main()并将其传递给返回盒装Future. 然而,我遇到了终身和借贷问题,似乎无法彻底解决这个问题。
这是我的结构和函数:
extern crate futures; // 0.1.21
extern crate tokio_core; // 0.1.17
use futures::{future::ok, Future};
pub struct SomeStruct {
some_val: u32,
}
impl SomeStruct {
pub fn do_something(&self, value: u32) -> u32 {
// Do some work
return self.some_val + value;
}
}
fn main() {
let core = tokio_core::reactor::Core::new().unwrap();
let my_struct = SomeStruct { some_val: 10 };
let future = get_future(&my_struct);
core.run(future);
let future2 = get_future(&my_struct);
core.run(future2);
}
fn get_future(some_struct: &SomeStruct) -> Box<Future<Item = …Run Code Online (Sandbox Code Playgroud)