如何将枚举引用转换为数字? [英] How do I convert an enum reference to a number?

查看:112
本文介绍了如何将枚举引用转换为数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个枚举:

enum Foo {
    Bar = 1,
}

如何将对此枚举的引用转换为要在数学中使用的整数?

How do I convert a reference to this enum into an integer to be used in math?

fn f(foo: &Foo) {
    let f = foo as u8;  // error[E0606]: casting `&Foo` as `u8` is invalid
    let f = foo as &u8; // error[E0605]: non-primitive cast: `&Foo` as `&u8`
    let f = *foo as u8; // error[E0507]: cannot move out of borrowed content
}

推荐答案

*foo as u8 是正确的,但是你必须实现 Copy 否则你会留下无效的引用.

*foo as u8 is correct, but you have to implement Copy because otherwise you would leave behind an invalid reference.

#[derive(Copy, Clone)]
enum Foo {
    Bar = 1,
}

fn f(foo: &Foo) -> u8 {
    *foo as u8
}

由于您的枚举将是一个非常轻量级的对象,您无论如何都应该通过值传递它,为此您还需要Copy.

Since your enum will be a very lightweight object you should pass it around by value anyway, for which you would need Copy as well.

这篇关于如何将枚举引用转换为数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆