帖子
分享您的知识。
andreweth.234
Dec 31, 2024
专家问答
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
2
2
分享
评论
答案
2deriss174
Dec 31 2024, 21:02发生此错误是因为 “值” 字段是模块 “dif_module:: contract” 的私有字段. 在 Rust 中,结构字段默认是私有的,这意味着它们只能在定义它们的同一模块中访问. 要解决这个问题,你可以在 “dif_module:: contract” 模块中定义一个公共获取器函数,该函数返回你需要的值. 这允许其他模块调用此函数并间接访问该字段.
1
最佳答案
评论
tomek182
Jan 1 2025, 07:07解决这个问题的另一种方法是将字段本身的可见性更改为公开,前提是这样做既安全又合适. 但是,通常定义公共 getter 方法是一种更好的做法,因为它可以更好地控制如何访问和操作字段值.
1
评论
你知道答案吗?
请登录并分享。
Sui is a Layer 1 protocol blockchain designed as the first internet-scale programmable blockchain platform.
386帖子540答案