如何获得用户定义结构的大小? (大小) [英] How to get the size of a user defined struct? (sizeof)
问题描述
我有一个带有C表示的结构:
I've got a structure with C representation:
struct Scard_IO_Request {
proto: u32,
pciLength: u32
}
当我想使用以下命令询问sizeof
时(如C sizeof()
中的情况):
when I want to ask the sizeof
(like in C sizeof()
) using:
mem::sizeof<Scard_IO_Request>();
我收到编译错误:
"error: `sizeof` is a reserved keyword"
为什么不能像在C中那样使用此sizeof
函数?有其他选择吗?
Why can't I use this sizeof
function like in C? Is there an alternative?
推荐答案
有两个原因:
-
没有像
sizeof
这样的功能,因此编译器将很难调用它.
There is no such function as "
sizeof
", so the compiler is going to have a rather difficult time calling it.
那不是您调用通用函数的方式.
That's not how you invoke generic functions.
如果您查看mem::size_of
的文档(即使您搜索"sizeof",也可以找到该文档) ),您会看到它包含一个可运行示例告诉您如何调用它.对于后代,有问题的示例是:
If you check the documentation for mem::size_of
(which you can find even if you search for "sizeof"), you will see that it includes a runnable example which shows you how to call it. For posterity, the example in question is:
fn main() {
use std::mem;
assert_eq!(4, mem::size_of::<i32>());
}
在您的特定情况下,您将使用来获得该结构的大小
In your specific case, you'd get the size of that structure using
mem::size_of::<Scard_IO_Request>()
这篇关于如何获得用户定义结构的大小? (大小)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!