Wednesday 13 May 2015

Rust: the size of a struct

This code determines the size of a data structure in byte terms.

use std::mem;

#[allow(dead_code)]
pub struct AStruct {
  prop: u32
}

pub fn size_of_a_struct() -> usize {
  mem::size_of::<AStruct>()
}

#[cfg(test)]
mod test {
  use super::*;

  #[test]
  fn test_size() {
    let expected = 4 as usize;
    assert_eq!(expected, size_of_a_struct());
  }
}

Rust provides the size_of function to determine the size of a type.

This post is just a code snippet written by someone getting started. No promises are made about code quality. Version: rustc 1.0.0-beta.4 (850151a75 2015-04-30) (built 2015-04-30)

No comments:

Post a Comment

All comments are moderated