我对借贷和所有权感到困惑.在Rust 文档中有关引用和借用的内容
let mut x = 5;
{
let y = &mut x;
*y += 1;
}
println!("{}", x);
Run Code Online (Sandbox Code Playgroud)
他们说
println!可以借x.
我很困惑.如果println!借入x,为什么它通过x不&x?
我尝试在下面运行此代码
fn main() {
let mut x = 5;
{
let y = &mut x;
*y += 1;
}
println!("{}", &x);
}
Run Code Online (Sandbox Code Playgroud)
除了传递&x给代码之外,这段代码与上面的代码相同println!.它将'6'打印到控制台,这是正确的,与第一个代码的结果相同.
我目前正在研究Google的细丝工作系统。您可以在此处找到源代码。令我困惑的部分是这个requestExit()方法:
void JobSystem::requestExit() noexcept {
mExitRequested.store(true);
{ std::lock_guard<Mutex> lock(mLooperLock); }
mLooperCondition.notify_all();
{ std::lock_guard<Mutex> lock(mWaiterLock); }
mWaiterCondition.notify_all();
}
Run Code Online (Sandbox Code Playgroud)
我很困惑,为什么即使在锁定和解锁之间没有任何动作,也需要锁定和解锁。在任何情况下都需要这种空的锁定和解锁吗?
我现在正在学习 Rust。我想检查一下我对 Rust 所有权的理解。我对递归结构中的所有权和借用概念感到困惑。我在rustbyexample.com 中看到了这段代码
// Allow Cons and Nil to be referred to without namespacing
use List::{Cons, Nil};
// A linked list node, which can take on any of these two variants
enum List {
// Cons: Tuple struct that wraps an element and a pointer to the next node
Cons(u32, Box<List>),
// Nil: A node that signifies the end of the linked list
Nil,
}
// Methods can be attached to an enum
impl List { …Run Code Online (Sandbox Code Playgroud)