例如,我有一个简单的分类器
struct Clf {
x: f64,
}
Run Code Online (Sandbox Code Playgroud)
如果观察值小于x则分类器返回0,如果大于x则分类器返回1.
我现在想要为这个分类器实现call运算符.但是,该函数应该能够将float或vector作为参数.在向量的情况下,输出是0或1的向量,其具有与输入向量相同的大小.它应该像这样工作
let c = Clf { x: 0 };
let v = vec![-1, 0.5, 1];
println!("{}", c(0.5)); // prints 1
println!("{}", c(v)); // prints [0, 1, 1]
Run Code Online (Sandbox Code Playgroud)
我该怎么写呢
impl Fn for Clf {
extern "rust-call" fn call(/*...*/) {
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下?
use std::sync::mpsc::{Sender, Receiver};
use std::sync::mpsc;
use std::thread;
static NTHREADS: i32 = 3;
fn main() {
// Channels have two endpoints: the `Sender<T>` and the `Receiver<T>`,
// where `T` is the type of the message to be transferred
// (type annotation is superfluous)
let (tx, rx): (Sender<i32>, Receiver<i32>) = mpsc::channel();
for id in 0..NTHREADS {
// The sender endpoint can be copied
let thread_tx = tx.clone();
// Each thread will send its id via the channel …Run Code Online (Sandbox Code Playgroud) 我正在写一个小型的战略游戏,但我在实现循环链表方面存在问题.
游戏涉及几个人一个接一个地采取行动,直到比赛结束.我可以通过使用循环链表来完成,其中每个元素都是一个引用下一个玩家的玩家.结构是这样的:
#[derive(Debug, Clone)]
struct Player {
name: String,
killed: bool,
next: Option<Box<Player>>,
}
Run Code Online (Sandbox Code Playgroud)
我还想要一个指向当前活动播放器的指针并能够修改它的状态,但我认为Rust不允许我对同一个对象有两个可变引用,因为每个播放器已经有一个对下一个播放器的可变引用.
我想出的是,我可以使用一个简单的可变引用,该引用Box由其之前的播放器拥有并指向当前播放器.我写了一个简单的main函数,出现问题:
fn main() {
let mut p3: Player = Player {
name: "C".to_string(),
killed: false,
next: None,
};
let mut p2: Player = Player {
name: "B".to_string(),
killed: false,
next: Some(unsafe { Box::from_raw(&mut p3) }),
};
let mut p1: Player = Player {
name: "A".to_string(),
killed: false,
next: Some(unsafe { Box::from_raw(&mut p2) }),
};
p3.next = Some(unsafe { Box::from_raw(&mut p1) });
println!("GAME STARTED!"); …Run Code Online (Sandbox Code Playgroud)