Post
Share your knowledge.
How to access a private struct field in Rust?
I'm working on a Rust project and encountered an error saying 'Invalid access of field 'value' on the struct 'dif_module::contract::Struct'. The field 'value' can only be accessed within the module 'dif_module::contract'. Why is this happening and how can I fix it?
- Sui
Answers
2This error occurs because the field 'value' is private to the module 'dif_module::contract'. In Rust, struct fields are private by default, meaning they can only be accessed within the same module they are defined in. To resolve this, you can define a public getter function within the 'dif_module::contract' module that returns the value you need. This allows other modules to call this function and access the field indirectly.
Another way to fix this is to change the visibility of the field itself to public if it is safe and appropriate to do so. However, often defining a public getter method is a better practice as it provides more control over how the field value is accessed and manipulated.
Do you know the answer?
Please log in and share it.
Sui is a Layer 1 protocol blockchain designed as the first internet-scale programmable blockchain platform.
- Why does BCS require exact field order for deserialization when Move structs have named fields?53
- Multiple Source Verification Errors" in Sui Move Module Publications - Automated Error Resolution43
- Sui Transaction Failing: Objects Reserved for Another Transaction25
- How do ability constraints interact with dynamic fields in heterogeneous collections?05