Difference betwene struct and enum

2023-04-19

According to phined:

In Rust, struct and enum serve different purposes and have different behaviors:

  1. Memory layout:

    • struct: The size of a struct is the sum of the sizes of its members, plus any padding for alignment. stackoverflow.com
    • enum: The size of an enum is the size of the largest variant plus the variant identifier. stackoverflow.com
  2. Usage:

    • struct: Represents an "AND" combination of its fields. It is used to encapsulate related properties into one unified data type. reddit.com
    • enum: Represents an "OR" combination of its variants. It is used when a value can be one of several possible types. reddit.com
  3. Type aliases: Type aliases can be used with enums to simplify long or generic names. doc.rust-lang.org

  4. Optimizations: Rust's compiler can optimize enums for memory usage and safety, whereas structs do not have the same level of optimization. reddit.com

  5. Match statement: Enums can be used directly with match statements, which is one of the primary use cases for enums. reddit.com

Here are examples of each:

#![allow(unused)]
fn main() {
// Struct example 
struct Point { 
	x: i32,
	y: i32, 
} // Enum example 
enum Shape {     
	Circle(f32),     
	Rectangle(f32, f32),     
	Triangle(f32, f32), 
}
}

source

In summary, use struct when you want to group related properties into a single data type, and use enum when you want to represent a value that can be one of several possible types.

So it basically mean the struct in rust is like java's object and enum is kind of like a super class.