rustRust struct of any type example
A struct
is a custom data type in Rust that allows you to group related data together. It is similar to a class in other languages. Here is an example of a struct
that stores information about a person:
struct Person {
name: String,
age: u8
}
This struct
has two fields, name
and age
, both of which are of type String
and u8
respectively. The name
field stores the person's name as a String
and the age
field stores the person's age as an u8
(unsigned 8-bit integer).
To create an instance of this struct
, we can use the new
keyword:
let person = Person {
name: String::from("John"),
age: 30
};
This creates a Person
instance with the name John
and age 30
. We can then access the fields of this instance using dot notation:
println!("Name: {}", person.name);
println!("Age: {}", person.age);
This will print out the following:
Name: John
Age: 30
We can also create methods on our struct
s to perform operations on the data they contain. For example, we could create a greet
method that prints out a greeting for the person:
impl Person {
fn greet(&self) {
println!("Hello, my name is {} and I am {} years old.", self.name, self.age);
}
}
We can then call this method on our person
instance:
person.greet();
This will print out the following:
Hello, my name is John and I am 30 years old.
Helpful links
Related
- Rust struct with one field example
- How to extend struct from another struct in Rust
- How to convert struct to protobuf in Rust
- How to copy struct in Rust
- How to write struct to json file in Rust
- How to convert struct to bytes in Rust
- Example of struct private field in Rust
- How to serialize struct to json in Rust
- Example of struct with vector field in Rust
- Example of struct of structs in Rust
More of Rust
- How to replace a capture group using Rust regex?
- How to match whitespace with a regex in Rust?
- How to match a URL with a regex in Rust?
- How to use regex lookahead in Rust?
- How to get a capture group using Rust regex?
- How to replace all matches using Rust regex?
- How to use regex lookbehind in Rust?
- How to match the end of a line in a Rust regex?
- How to replace strings using Rust regex?
- How to split a string with Rust regex?
See more codes...