Error: pointers cannot be cast to integers during const eval

I feel like this process is unnecessarily difficult to do.

I've got a static. I'm trying to get its memory address (as a u64) to send to a struct that I (don't) have control over. I can't use transmute (I don't think anyway) because I'm in a const context. So I tried TERMINAL_TAG as *const _ as u64, and the trivial cast linter complains. So I try changing it to addr_of!(TERMINAL_TAG) as u64 and I get this error. Rust hints that it could be done through coercion but I can't figure out how to coerce it like that in a way that will make the compiler happy. Am I overlooking something?

1 Like

This is intentional, because at this point the addresses don't exist (or more specifically, addresses of temporary fake objects used by the const eval interpreter have nothing to do with the addresses that these items will eventually have at run time).

Things are laid out in executable's memory after the const eval. Statics may not even have any address at all during compilation, and will be assigned one by the linker, long after the compilation is finished.


Yes. You are forgetting about the fact that address of variable doesn't exist during compilation, it doesn't exist when you are linking program it only exist when you run your program.

But then… how can one static variable ever include address of another static variable? The answer is simple yet complex: loader which loads your executable can, actually, do that.

But it's pretty limited: you can, basically, put address of some static structure in some other static structure (with offset).

And if you allow conversion from address to u64 in const context then you would open huge can of worms: e.g. if you would take addresses of two fields and subtract them — that can be supported, if you want to subtract addresses of two arbitrary variables — that wouldn't work if you have no idea if they are in the same segment or not.

And, of course, if you store these addresses in some other static — compiler would need to remember that this u64 is not just any u64, but very special u64 with bunch of additional limitations.

All in all… enormous amount of work for very obscure feature. That's why both C++ and Rust forbid such transformation in constexpr context.

1 Like

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.