在下面的代码中,函数指针和我认为的"函数引用"似乎具有相同的语义:
#include <iostream>
using std::cout;
void func(int a) {
cout << "Hello" << a << '\n';
}
void func2(int a) {
cout << "Hi" << a << '\n';
}
int main() {
void (& f_ref)(int) = func;
void (* f_ptr)(int) = func;
// what i expected to be, and is, correct:
f_ref(1);
(*f_ptr)(2);
// what i expected to be, and is not, wrong:
(*f_ref)(4); // i even added more stars here like (****f_ref)(4)
f_ptr(3); // everything just works!
// all …Run Code Online (Sandbox Code Playgroud) 以下代码段给出了一个错误:
use std::rc::Rc;
// Definition of Cat, Dog, and Animal (see the last code block)
// ...
type RcAnimal = Rc<Box<Animal>>;
fn new_rc_animal<T>(animal: T) -> RcAnimal
where
T: Animal /* + 'static */ // works fine if uncommented
{
Rc::new(Box::new(animal) as Box<Animal>)
}
fn main() {
let dog: RcAnimal = new_rc_animal(Dog);
let cat: RcAnimal = new_rc_animal(Cat);
let mut v: Vec<RcAnimal> = Vec::new();
v.push(cat.clone());
v.push(dog.clone());
for animal in v.iter() {
println!("{}", (**animal).make_sound());
}
}
Run Code Online (Sandbox Code Playgroud)
error[E0310]: the parameter type `T` may not …Run Code Online (Sandbox Code Playgroud) unreachable!宏的存在纯粹是为了在阅读代码时清晰起见,还是它提供了任何功能上的优势?
请考虑以下代码(Playground版本):
use std::cell::Cell;
struct Foo(u32);
#[derive(Clone, Copy)]
struct FooRef<'a>(&'a Foo);
// the body of these functions don't matter
fn testa<'a>(x: &FooRef<'a>, y: &'a Foo) { x; }
fn testa_mut<'a>(x: &mut FooRef<'a>, y: &'a Foo) { *x = FooRef(y); }
fn testb<'a>(x: &Cell<FooRef<'a>>, y: &'a Foo) { x.set(FooRef(y)); }
fn main() {
let u1 = Foo(3);
let u2 = Foo(5);
let mut a = FooRef(&u1);
let b = Cell::new(FooRef(&u1));
// try one of the following 3 statements
testa(&a, &u2); …Run Code Online (Sandbox Code Playgroud) 我有一个“主”进程和一些“工作”进程,我想在它们之间传递一些消息。这些消息可以是二进制 blob,但每个消息都有固定的大小。我想要一个抽象,它可以为我整齐地缓冲和分离每条消息。我不想在 TCP 之上发明自己的协议,而且我找不到任何可跨语言移植的简单+轻量级解决方案。(到目前为止,“主”进程是 Node.js 服务器,“工作”进程计划使用 Python。)
更具体地讲,为什么没有 Arc<T>实现from_raw与动态调整T,同时Box<T> 呢?
use std::sync::Arc;
fn main() {
let x = vec![1, 2, 3].into_boxed_slice();
let y = Box::into_raw(x);
let z = unsafe { Arc::from_raw(y) }; // ERROR
}
Run Code Online (Sandbox Code Playgroud)
(玩)
正如在注释中指出的那样,Arc::from_raw 必须使用指针来自Arc::into_raw,所以上面的例子没有意义.我原来的问题(是否有可能Arc<[T]>从a 创建Vec<T>)仍然存在:这是可能的,如果没有,为什么?
我有一个看起来像这样的结构:
pub struct MyStruct<F>
where
F: Fn(usize) -> f64,
{
field: usize,
mapper: F,
// fields omitted
}
Run Code Online (Sandbox Code Playgroud)
我如何实现Clone这个结构?
我发现复制函数体的一种方法是:
let mapper = |x| (mystruct.mapper)(x);
Run Code Online (Sandbox Code Playgroud)
但这会导致mapper与mystruct.mapper.