How to get the size of a user defined struct? (sizeof)

我与影子孤独终老i 提交于 2019-12-23 14:24:06

问题


I've got a structure with C representation:

struct Scard_IO_Request {
    proto: u32,
    pciLength: u32
}

when I want to ask the sizeof (like in C sizeof()) using:

mem::sizeof<Scard_IO_Request>();

I get compilation error:

"error: `sizeof` is a reserved keyword"

Why can't I use this sizeof function like in C? Is there an alternative?


回答1:


For two reasons:

  1. There is no such function as "sizeof", so the compiler is going to have a rather difficult time calling it.

  2. That's not how you invoke generic functions.

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>()


来源:https://stackoverflow.com/questions/36664327/how-to-get-the-size-of-a-user-defined-struct-sizeof

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!