advance/into-types/enum-int #726
Replies: 12 comments 14 replies
-
谁能解释一下那个宏的代码? |
Beta Was this translation helpful? Give feedback.
-
所以解释一下 A = 1 是什么语法?一开始我以为是宏定义的语法,但是看了开头的例子,没有用到宏之前,就有使用到这个语法了。 |
Beta Was this translation helpful? Give feedback.
-
学rust这么久以赖,前面的复杂的都能忍,但是,一个整数与枚举转换这种非常常用的场景,都要引用第三方库。 |
Beta Was this translation helpful? Give feedback.
-
这里的 x 是什么啊 |
Beta Was this translation helpful? Give feedback.
-
TryInto + 宏解决这个问题在在实践中会用到吗?TryInto 里面的 match 代码感觉和外面的差不多啊,直接写有什么不妥当的地方吗? |
Beta Was this translation helpful? Give feedback.
-
感觉没有那么麻烦,也不需要第三方库啊。况且用了第三方库还是要写那么多代码,一点没方便。 #[repr(u8)]
#[derive(Debug)]
enum State {
State0,
State1,
State2,
State3,
State4,
}
impl State {
fn into_u8(self) -> u8 {
self as u8
}
fn from_u8(v: u8) -> Option<State> {
match v {
0 => Some(State::State0),
1 => Some(State::State1),
2 => Some(State::State2),
3 => Some(State::State3),
4 => Some(State::State4),
_ => None,
}
}
}
fn main() {
let state = State::State3;
let mut value = state.into_u8();
println!("value = {:?}", value);
value += 1;
State::from_u8(value).map(|state| println!("state = {:?}", state));
} |
Beta Was this translation helpful? Give feedback.
-
摘自:stackOverflow https://stackoverflow.com/questions/28028854/how-do-i-match-enum-values-with-an-integer |
Beta Was this translation helpful? Give feedback.
-
为什么不直接写?TryFrom + 宏还得绕一圈
|
Beta Was this translation helpful? Give feedback.
-
let mut x=HashMap::new(); |
Beta Was this translation helpful? Give feedback.
-
如果 std::mem::transmute 转入了 不在enum里的整数,会怎样 |
Beta Was this translation helpful? Give feedback.
-
advance/into-types/enum-int
https://course.rs/advance/into-types/enum-int.html
Beta Was this translation helpful? Give feedback.
All reactions