Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Constants

IDL constants are mapped directly to Rust constants. Rust supports octal, hexadecimal and decimal integer literals. String constants will be mapped to string slices instead of String.

// IDL
const int32 MY_DECIMAL = 123;
const int32 MY_HEX = 0xFFF;
const int32 MY_OCTAL = 0655;
const string MY_STRING = "my string";
const octet MY_ARRAY[4] = {0, 1, 2, 3};
#![allow(unused)]
fn main() {
// Rust
pub const MY_DECIMAL: i32 = 123;
pub const MY_HEX: i32 = 0xFFF;
pub const MY_OCTAL: i32 = 0o655;
pub const MY_STRING: &str = "my_string";
pub const MY_ARRAY: [u8; 4] = [0, 1, 2, 3];
}

Complex types

Constants can only be used for types that can be constructed at compile-time, i.e. types whose constructor is const. For non-const types, statics must be used instead.

Rust does not permit code execution before main, i.e. dynamic initialization of statics must happen afterwards. Constants that require dynamic initialization – i.e. vectors and complex IDL types – must thus be explicitly initialized the first time the member is accessed. To avoid data races, the variable can be initialized using std::sync::LazyLock, a synchronization primitive which lazily initializes the value on first access. This is only done for types which contain non-const-constructible members.

// IDL
struct MyTrivialStruct {
    int32 x;
    int32 y;
    int32 z;
};

struct MyComplexStruct {
    string my_str;
};

const MyTrivialStruct MY_TRIVIAL_CONST = { ... };
const MyComplexStruct MY_COMPLEX_CONST = { ... };
#![allow(unused)]
fn main() {
// Rust
pub const MY_TRIVIAL_CONST: MyTrivialStruct = MyTrivialStruct { ... };

pub static MY_COMPLEX_CONST: ::std::sync::LazyLock<MyComplexStruct> =
    ::std::sync::LazyLock::new(|| MyComplexStruct { ... });
}