DEV Community

Sivakumar
Sivakumar

Posted on • Updated on

Working with Struct in Rust

In this blog post, let us explore how to work with Struct in Rust

Create Struct type

Struct is equivalent to Class in Java language. It is a type composed of other types. There are 3 different ways we can create Struct in Rust

Named fields

This is more common approach we create Struct. Each field defined has a name and a type. It is possible to declare a field with pub and those such fields are visible to other modules

struct Employee {
    name: String,
    age: i32,
    dept: String,
}
Enter fullscreen mode Exit fullscreen mode
Tuple Structs

It is similar to regular structs except they don't have any defined name. The fields can be accessible by using its index position starting with 0

struct TupleStruct(String, i32, String);
Enter fullscreen mode Exit fullscreen mode
Unit Structs

Unit Structs as name implies, it doesn't have any fields and has zero-size and they are commonly used as markers. This can be instantiated. It is useful when you need to implement a trait but don't want to store any data inside it.

struct UnitStruct;
Enter fullscreen mode Exit fullscreen mode

Constructor method for Struct

Struct can be initialized by assigning values to each of its member fields or add constructor method named new. This method takes argument values and returns itself.

impl Employee {
    pub fn new(name: String, age: i32, dept: String) -> Self {
        Self { name, age, dept }
    }
}
Enter fullscreen mode Exit fullscreen mode

Add Behaviors to Struct

Struct without any methods doesn't make any sense. It is possible to add methods to Struct. Struct can also implement Trait's methods

In this below example, we're implementing Debug and Display trait for our Struct

impl fmt::Debug for Employee {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Employee")
            .field("Name", &self.name)
            .field("Age", &self.age)
            .field("Department", &self.dept)
            .finish()
    }
}

impl Display for Employee {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "Employee [Name: {}, Age: {}, Department: {}]",
            self.name, self.age, self.dept
        )
    }
}
Enter fullscreen mode Exit fullscreen mode

All the code examples can be found in this link

Please feel free to share your feedback.

Happy reading!!!

Top comments (0)