How to share a const in Rust?

How does one do something like this in Rust?

// file.c
char const * const strings[10] = {
    "str1", ...
}
// file.h
extern char const * const strings[10];

The reference mentions that constant items in Rust are not associated with a particular location in memory, but what if you do want to have it in memory?

Use static with a constant initializer:

static STRINGS: [&str; 10] = [ "str0", "str1", ... ];
3 Likes

Ah right, but it would need to be

pub static STRINGS: [&str; 10] = [ "str0", "str1", ... ];

Right?

Yes, it needs pub to be shared outside the current module.

Since static in C kind of means "private" I didn't even think of that.

Would strings be in RAM though? I'd like the array to be stored in flash memory (embedded context).

For ELF, they would be in the .rodata section. That might map to flash memory on your device, but I'm not sure.

2 Likes

Cool, thanks :slight_smile:

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.