How to get the value of a Struct without named field?

Hi,

I am using Legion and it has a struct defined like below,
pub struct Entity(NonZeroU64);

When I visualize the entity in the debug window, it shows a value. However, I don't see a straight forward method to access it. Can you help in accessing the value?

I am expecting something like below,
let val: u64 = entity;

You can access in the same way you access something inside tuple - by using the my_entity.0 syntax.

See thee chapter on Tuple Index Expressions in the Rust Reference for more details.

1 Like

Thanks Michael. However, it is throwing an error field 0 of struct legion::Entity is private

Hi, there doesn't seem to be a method to access the inner value directly, probably by design:

An opaque identifier for an entity.

But it is repr(transparent) so you could transmute to a NonZeroU64 and get a u64 from there.
I wouldn't say it's a pretty solution :sweat_smile:

Someone might be able to help more if you explain what you want to do with the inner value.

Thanks @leudz. I have a function which is called for each entity. At the end of the function, I am inserting processed data into Sled. Since I want a unique key, I thought I will use the Entity.0 as the unique key so in other parts of the code, I can use this Entity.0 to fetch the processed data from Sled.

I directly tried sled.insert(entity, my_data) which didn't work as Sled is expecting &[u8]

If it is private, the library authors have deliberately chosen to not let users access that inner field.

Often this is done because the number is an internal implementation detail, and letting users read/modify it could cause them to write code that violates assumptions made by Legion.

I don't think we should be recommending to use transmute() to hack around privacy.

Legion actually has a CustomEntitySerializer implementation which will transform an Entity into a UUID you can pass to sled.

1 Like

Thanks @Michael-F-Bryan. Does this means I have to add below lines in the function?

let c = Canon::default();
let a = c.get_name(*entity).expect(&err);

Will calling Canon::default() inside function, changes the UUID?

You would need to check the source code or documentation to see whether the UUIDs are deterministic. I think it should be fine as long as you use the same Canon instance for serializing all your entities.

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.