类型铸造选项中的生锈

发布于 2025-01-24 21:55:02 字数 366 浏览 4 评论 0原文

如何在Rust中施放可选值?

这就是我想到的,它确实有效,但我认为必须有一种更优雅的方式。

pub fn option_t_to_i32_option<T1, T2>(optional_val: Option<T1>) -> Option<T2>
where
    T2: From<T1>,
{
    return match optional_val {
        Some(val) => Some(T2::from(val)),
        None => None,
    };
}

How do I cast optional values in rust?

This is what I came up with, which does work, but I think there must be a more elegant way.

pub fn option_t_to_i32_option<T1, T2>(optional_val: Option<T1>) -> Option<T2>
where
    T2: From<T1>,
{
    return match optional_val {
        Some(val) => Some(T2::from(val)),
        None => None,
    };
}

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

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

发布评论

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

评论(1

深府石板幽径 2025-01-31 21:55:03

只是map in :: in :: in您的约束:

pub fn option_t_to_i32_option<T1, T2>(optional_val: Option<T1>) -> Option<T2>
where
    T2: From<T1>,
{
    optional_val.map(Into::into)
}

Playground> Playground

根据您的功能名称,也许您想实际上将输出类型与i32 i32

pub fn option_t_to_i32_option<T1>(optional_val: Option<T1>) -> Option<i32>
where
    T1: Into<i32>,
{
    optional_val.map(Into::into)
}

5b4e041d1b41d1b4d0286b745835835cca1165宁愿使用_。MAP(in :: in :: in ton)无论您需要去option&lt; t&gt; =&gt;选项&lt; i32&gt;

Just map Into::into for your constrains:

pub fn option_t_to_i32_option<T1, T2>(optional_val: Option<T1>) -> Option<T2>
where
    T2: From<T1>,
{
    optional_val.map(Into::into)
}

Playground

As per your function name, maybe you would like to actually match the output type to i32:

pub fn option_t_to_i32_option<T1>(optional_val: Option<T1>) -> Option<i32>
where
    T1: Into<i32>,
{
    optional_val.map(Into::into)
}

Playground

Btw, since this is a wrapper, you could rather use _.map(Into::into) wherever you need to go Option<T> => Option<i32> instead.

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