返回生锈的可变地图参考

发布于 2025-01-25 10:54:07 字数 885 浏览 3 评论 0原文

我的目标是从编程中添加一些DEV依赖项。

我正在使用toml板条箱(toml = {version =“ 0.5.8”,features = [“ preserve_order”]})。

这是我试图获取DEV依赖项地图或在未定义开发DEP时创建新地图的代码的一部分。

let mut dev_deps = cargo_toml_content
    .get_mut("dev-dependencies")
    .and_then(Value::as_table_mut)
    .unwrap_or_else(|| ???);

value :: as_table_mut代码的一部分返回option&lt;&amp; amp; mut table;其中table> table> table is map&lt; string,value&gt; <<<<<< /代码>。如果该函数没有返回任何内容,我想在unwrap_or_else阻止并返回它的情况下初始化新地图。

我能够返回新的地图 /表,但我不知道如何返回地图的可变参考。当我使用类似的内容时,我正在努力争取所有者诸如之类的事情返回当前函数拥有的数据

...
.unwrap_or_else(|| {
    let mut table = Table::default();
    &mut table
});

那么(以及如何(以及如何)我该怎么做才能正确返回表的可变参考?还是关于如何解决此问题有更好的解决方案?

My goal is to add some dev dependencies to Cargo.toml programatically.

I am using the toml crate (toml = { version = "0.5.8", features = ["preserve_order"] }).

Here is the part of code where I am trying to get the Map of dev dependencies or create a new Map when dev deps are not defined.

let mut dev_deps = cargo_toml_content
    .get_mut("dev-dependencies")
    .and_then(Value::as_table_mut)
    .unwrap_or_else(|| ???);

The Value::as_table_mut part of code returns Option<&mut Table> where Table is Map<String, Value>. If the function doesnt return anything, I would like to initialize a new Map in unwrap_or_else block and return it.

I am able to return a new Map / Table but I dont know how to return a mutable reference of the Map. I am struggling with the ownerhip things like returns a reference to data owned by the current function when I use something like this:

...
.unwrap_or_else(|| {
    let mut table = Table::default();
    &mut table
});

So what (and how) should I do to correctly return the mutable reference of Table? Or is there a better solution on how to solve this problem?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

清君侧 2025-02-01 10:54:07

您可以在回调之外创建地图:

let mut empty = Table::default();
let mut dev_deps = cargo_toml_content
    .get_mut("dev-dependencies")
    .and_then(Value::as_table_mut)
    .unwrap_or(&mut empty);

但是最好只有Match

如果您想在最后重新插入地图,那么最好从一开始就将其放在那里。

You can create the map outside of the callback:

let mut empty = Table::default();
let mut dev_deps = cargo_toml_content
    .get_mut("dev-dependencies")
    .and_then(Value::as_table_mut)
    .unwrap_or(&mut empty);

But it's better to just match.

If you want to re-insert the map at the end anyway, it will be better to put it there from the beginning.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文