Rust 中的冒号运算符与 C 中的冒号运算符有什么相似之处? [英] What is similar in Rust to the colon operator in C?
本文介绍了Rust 中的冒号运算符与 C 中的冒号运算符有什么相似之处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在 Rust 中表示这种代码?
How to represent this kind of code in Rust?
uint8_t pmport:4;
uint8_t rsv0:3;
uint8_t c:1;
我想将这 3 个值打包成一个 u8
.如何在 Rust 中实现这一点?
I want to pack these 3 values into a single u8
. How can this be achieved in Rust?
推荐答案
Rust 没有像 C 那样在语言中内置位域.但是,您可以使用像 bitfield 这样的 crate 来实现相同的目的.bitfield
宏允许您定义每个位域的类型、大小和访问器方法.
Rust does not have bit fields built into the language like C does.
However, you can use a crate like bitfield to achieve the same thing.
The bitfield
macro lets you define the types, size and accessor methods for each bit field.
#[macro_use] extern crate bitfield;
bitfield! {
struct Example(u8);
u8;
get_pmport, set_pmport: 3, 0; // bits 0-3
get_rsv0, set_rsv0: 6, 4; // bits 4-6
get_c, set_c: 7, 7; // bit 7
}
fn main() {
println!("size of Example: {}", ::std::mem::size_of::<Example>());
let mut e = Example(0);
println!("pmport: {}, rsv0: {}, c: {}", e.get_pmport(), e.get_rsv0(), e.get_c());
e.set_pmport(5);
println!("pmport: {}, rsv0: {}, c: {}", e.get_pmport(), e.get_rsv0(), e.get_c());
e.set_rsv0(3);
println!("pmport: {}, rsv0: {}, c: {}", e.get_pmport(), e.get_rsv0(), e.get_c());
e.set_c(1);
println!("pmport: {}, rsv0: {}, c: {}", e.get_pmport(), e.get_rsv0(), e.get_c());
e.set_rsv0(0);
println!("pmport: {}, rsv0: {}, c: {}", e.get_pmport(), e.get_rsv0(), e.get_c());
}
这篇关于Rust 中的冒号运算符与 C 中的冒号运算符有什么相似之处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文