rust named tuple

In Rust, a named tuple is a data structure that allows you to give names to each element in the tuple. This can be useful when you want to have a collection of values that are related to each other and you want to access them by their names instead of their positions in the tuple.

To define a named tuple in Rust, you can use the struct keyword followed by the name of the tuple and the names of its elements. For example:

struct Person {
    name: String,
    age: u32,
    city: String,
}

In this example, Person is the name of the named tuple, and it has three elements: name, age, and city. Each element has its own type, which is specified after the name using the : operator.

To create an instance of a named tuple, you can use the Person struct name followed by curly braces {} and specify the values for each element by using their names. For example:

let person = Person {
    name: String::from("John"),
    age: 25,
    city: String::from("New York"),
};

In this example, we create a Person named tuple with the name "John", age 25, and city "New York".

To access the values of a named tuple, you can use dot notation followed by the name of the element. For example:

println!("Name: {}", person.name);
println!("Age: {}", person.age);
println!("City: {}", person.city);

This will print the values of the elements in the named tuple.

Named tuples in Rust provide a way to organize related data in a structured manner, allowing for easier access and manipulation of the data.