What's the idiomatic way to store array of global constant objects?


#1

I have object, say struct Obj.
I want to make global constant array(not Vec) of that objects
My code

However, array consisting of references is not very pleasant to use.
Is there any other(idiomatic) ways to do this task?


#2

You can make it an object instead of a reference there. Accessing those objects will give you references, but that’s fine (IMO).


#3

You can use a global static array like this

static list: [Obj; 1] = [
    Obj {}
];

or a global static slice like this

const LIST: &[Obj] = &[
    Obj {}
];

for the difference between static and const, static creates a value in the binary where const gets always inlined.


#4

Is there a way to use String in Obj?
When I do have const ... { field: String::from("...") },

it outputs:
error[E0015]: calls in constants are limited to constant functions, struct and enum constructors

Neither is it possible to use static, it outputs the same error.

Even If I initialise it in separate routine, it would require “unsafe”.


#5

Not today - it may be possible in the future. You can use string constants though.

If you want dynamically constructed strings then take a look at the lazy_static crate.


#6

What’s exact syntax for string constant? As I know, “…string…” is reference, not String.


#7

A string literal basically: “this is an example”. Using your example earlier: https://play.rust-lang.org/?gist=2fa7a7305f3fd60c6a5619d651d83bea&version=stable


#8

Why can’t one use String in place of &'static str and when to use which?


#9

I suggest googling this as it’s a common question.

But, basically (I’m going to omit some stuff, like the UTF-8 aspect) a String is an owned string - it’s dynamically allocated on the heap, at runtime (and thus cannot be in a const expression at the moment), and owns that memory. If you’re the owner of that String or have a mutable reference to it, you can mutate it.

&str is a string slice - can also be considered/called a string view. It’s a reference to a string, and doesn’t own it; you cannot, eg, append to the backing string.

A &'static str is a special type of string slice - a string constant/literal. It’s a string that’s directly embedded in the binary and is alive for the duration of the program. This is why you can use it in const expressions/contexts.


#10

Thanks, now it’s clear.