小编kev*_*nyu的帖子

println!借用或拥有变量?

我对借贷和所有权感到困惑.在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'打印到控制台,这是正确的,与第一个代码的结果相同.

ownership rust

39
推荐指数
1
解决办法
2219
查看次数

为什么在执行条件变量通知之前我们需要一个空的std :: lock_guard?

我目前正在研究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)

我很困惑,为什么即使在锁定和解锁之间没有任何动作,也需要锁定和解锁。在任何情况下都需要这种空的锁定和解锁吗?

c++ concurrency mutex condition-variable

8
推荐指数
1
解决办法
135
查看次数

谁拥有堆中的 Box?

我现在正在学习 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)

rust

5
推荐指数
1
解决办法
299
查看次数

标签 统计

rust ×2

c++ ×1

concurrency ×1

condition-variable ×1

mutex ×1

ownership ×1