我有一个值,我想在我自己的类型中存储该值以及对该值内部内容的引用:
struct Thing {
count: u32,
}
struct Combined<'a>(Thing, &'a u32);
fn make_combined<'a>() -> Combined<'a> {
let thing = Thing { count: 42 };
Combined(thing, &thing.count)
}
Run Code Online (Sandbox Code Playgroud)
有时候,我有一个值,我想在同一个结构中存储该值和对该值的引用:
struct Combined<'a>(Thing, &'a Thing);
fn make_combined<'a>() -> Combined<'a> {
let thing = Thing::new();
Combined(thing, &thing)
}
Run Code Online (Sandbox Code Playgroud)
有时,我甚至没有参考该值,我得到同样的错误:
struct Combined<'a>(Parent, Child<'a>);
fn make_combined<'a>() -> Combined<'a> {
let parent = Parent::new();
let child = parent.child();
Combined(parent, child)
}
Run Code Online (Sandbox Code Playgroud)
在每种情况下,我都会收到一个错误,即其中一个值"活不够长".这个错误是什么意思?
哪些具体条件为闭合来实现Fn,FnMut和FnOnce特质?
那是:
FnOnce特性?FnMut特性?Fn特性?例如,改变它的主体上的闭包状态会使编译器无法实现Fn它.
甲FnMut闭合无法克隆,出于显而易见的原因,但Fn封闭件具有一个不可变的范围; 有没有办法创建一个Fn闭包的"重复" ?
尝试克隆它会导致:
error[E0599]: no method named `clone` found for type `std::boxed::Box<std::ops::Fn(i8, i8) -> i8 + std::marker::Send + 'static>` in the current scope
--> src/main.rs:22:25
|
22 | fp: self.fp.clone(),
| ^^^^^
|
= note: self.fp is a function, perhaps you wish to call it
= note: the method `clone` exists but the following trait bounds were not satisfied:
`std::boxed::Box<std::ops::Fn(i8, i8) -> i8 + std::marker::Send> : std::clone::Clone`
Run Code Online (Sandbox Code Playgroud)
以某种方式将原始指针传递给Fn周围是安全的,例如:
let func_pnt = …Run Code Online (Sandbox Code Playgroud) 在下面的例子中:
struct Foo {
a: [u64; 100000],
}
fn foo(mut f: Foo) -> Foo {
f.a[0] = 99999;
f.a[1] = 99999;
println!("{:?}", &mut f as *mut Foo);
for i in 0..f.a[0] {
f.a[i as usize] = 21444;
}
return f;
}
fn main(){
let mut f = Foo {
a:[0;100000]
};
println!("{:?}", &mut f as *mut Foo);
f = foo(f);
println!("{:?}", &mut f as *mut Foo);
}
Run Code Online (Sandbox Code Playgroud)
我发现在传入函数之前和之后foo,地址f是不同的.为什么Rust会在任何地方复制这么大的结构但实际上不会移动它(或实现这种优化)?
我理解堆栈内存是如何工作的.但是根据Rust所有权提供的信息,我认为可以避免副本.编译器不必要地复制数组两次.这可以是Rust编译器的优化吗?
我有一个看起来像这样的结构:
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.