Logo

Developer learning path

Rust

Tuple Structs in Rust

Tuple Structs

55

#description

Sure, I'd be happy to explain Tuple Structs in Rust.

In Rust, a Tuple Struct is similar to a struct, but it is defined using a tuple syntax. It is a lightweight way of defining a struct-like construct that doesn't have any named fields.

Here's an example of how you can define a Tuple Struct in Rust:

                    
struct Employee(String, u32);

fn main() {
  let employee = Employee("John Doe".to_owned(), 28);
  println!("Employee name: {}, Age: {}", employee.0, employee.1);
}
                  

In this example, we have defined a struct named Employee using a tuple syntax. The Employee struct takes two parameters: a String for the employee name and a u32 for the employee age.

We then create an instance of the Employee struct, passing in the employee name and age as arguments. Finally, we print the employee name and age using the dot notation to access the values of the tuple struct.

The dot notation here is a way of accessing the values of the tuple struct. Since tuple structs don't have any named fields, Rust provides the dot notation based on the position of the fields in the tuple. In our example, employee.0 refers to the employee name and employee.1 refers to the employee age.

I hope that helps! Let me know if you have any further questions.

March 27, 2023

If you don't quite understand a paragraph in the lecture, just click on it and you can ask questions about it.

If you don't understand the whole question, click on the buttons below to get a new version of the explanation, practical examples, or to critique the question itself.