rustExample of struct private field in Rust
Struct private fields in Rust are fields that are not accessible outside of the struct. This can be controlled by using the pub
keyword - use it to make public fields, while skip it for private ones.
Example code
struct MyStruct {
pub field1: i32,
field2: i32,
}
fn main() {
let my_struct = MyStruct {
field1: 1,
field2: 2,
};
println!("field1: {}", my_struct.field1);
println!("field2: {}", my_struct.field2);
}
Output example
field1: 1
field2: 2
Code explanation
struct MyStruct {
: This is the start of the struct definition.pub field1: i32,
: This is the first field of the struct, which is public and can be accessed outside of the struct.field2: i32,
: This is the second field of the struct, which is private and cannot be accessed outside of the struct.let my_struct = MyStruct {
: This is the start of the struct initialization.field1: 1,
: This is the initialization of the first field of the struct.field2: 2,
: This is the initialization of the second field of the struct.println!("field1: {}", my_struct.field1);
: This is the print statement for the first field of the struct, which is public and can be accessed outside of the struct.println!("field2: {}", my_struct.field2);
: This is the print statement for the second field of the struct, which is private and cannot be accessed outside of the struct.
Helpful links
Related
- Example of struct of structs in Rust
- How to init zero struct in Rust
- Example of Rust struct with closure
- How to get struct value in Rust
- Rust struct without fields
- How to update struct in Rust
- Example of struct with vector field in Rust
- How to convert struct to protobuf in Rust
- How to convert struct to bytes in Rust
More of Rust
- How to get a capture group using Rust regex?
- How to match a URL with a regex in Rust?
- How to use regex to match a double quote in Rust?
- How to use regex to match a group in Rust?
- How to parse JSON string in Rust?
- How to use regex with bytes in Rust?
- How to implement PartialEq for a Rust HashMap?
- How to use a tuple as a key in a Rust HashMap?
- How to use a HashBrown with a Rust HashMap?
- How to convert a Rust HashMap to a JSON string?
See more codes...