gpt4 book ai didi

loops - 试图从 Rust 中的循环外部借用变量绑定(bind)

转载 作者:行者123 更新时间:2023-12-03 11:40:57 29 4
gpt4 key购买 nike

    // I want to use this...
let group = svg::node::element::Group::new();

for (index, character) in label_string.char_indices() {

let character = svg::node::Text::new(character);

let text = svg::node::element::Text::new()
.set("x", 0 + 16 * index)
.set("y", 20)
.set("font-family", "Hack")
.set("font-size", 16)
.set("fill", color::color(foreground_color))
.add(character);

// ...inside this for loop.
group.add(text);

}
但有人告诉我 use of moved value: group因为 value moved here, in previous iteration of loop .
这是有道理的。但我不知道怎么借 group反而。 for语法并没有给我任何方法来做到这一点,这些也不起作用:
    for (index, character) in label_string.char_indices() {
...
let group_ref = &group;
group_ref.add(text);
}
    let group_ref = &group;
for (index, character) in label_string.char_indices() {
...
group_ref.add(text);
}
注: Trying to borrow variable binding from outside of loop不回答这个问题。

最佳答案

svg::node::element::Group::add 具有以下签名:

impl Group {
pub fn add<T>(self, node: T) -> Self
where
T: Node,
{ /* ... */ }
}
从这个签名中我们可以看到该方法采用 self按值(不是按引用,如 &self&mut self ),这意味着当您调用 group.add(text)从循环中,将值移出 group变量(因为 add 方法需要取得所有权)。到下一次循环迭代时,变量中没有值,所以编译器会报错。
但是,我们也可以看到该方法返回 Self ,这表明我们得到了一个新值,我们可以重新分配给 group .这样,在迭代结束(和下一次开始)时,我们将在 group 中获得一个值。尚未移出的变量:
// note that we need this to be mut now, since we're reassigning within the loop
let mut group = svg::node::element::Group::new();

for (index, character) in label_string.char_indices() {
// ...

// since `group.add()` takes ownership of `group`, but returns a new value,
// we can just reassign to `group`, so that it is present for the next iteration
group = group.add(text);

}

关于loops - 试图从 Rust 中的循环外部借用变量绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66591578/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com