【问题标题】:How to convert Option<T> to Option<&T> in the most idiomatic way in Rust?如何在 Rust 中以最惯用的方式将 Option<T> 转换为 Option<&T>?
【发布时间】:2021-05-05 06:40:33
【问题描述】:

假设我有一个类型为Option&lt;T&gt; 的值x,如何将其转换为Option&lt;&amp;T&gt;?
我尝试使用map:

let result = x.map(|x| &x)
                       ^^ Error

但我得到了错误:

cannot return reference to function parameter `x`
returns a reference to data owned by the current function

【问题讨论】:

标签: rust


【解决方案1】:

经过反复试验,我找到了方法,即as_ref。

参考:https://doc.rust-lang.org/std/option/enum.Option.html#method.as_ref

【讨论】:

    猜你喜欢
    • 2018-12-22
    • 2019-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-14
    • 2014-03-24
    相关资源
    最近更新 更多