Search code examples
ruststructenumsrust-cargo

What is the difference between a Struct and an Enum in Rust


Coming from javascript/python I'm used to the idea of classes but am struggling to understand the difference between a Struct and an Enum.

For example I can define a 'class' with behaviours in similar ways

struct

// Defines the StartListen class
pub struct StartListen {
    socket: SocketAddr,
    listener: TcpListener,
}

// Implementation for StartListen class
impl StartListen {
    pub async fn new(socket: SocketAddr) -> Result<StartListen, StartListenError> {
        println!("Attempting to listen");

enum

// Defines the types of messages to expect
#[derive(Debug)]
pub enum RequestType {
    RequestWork {
        request_message: String,
        parameter: String,
        sender_timestamp: String,
    },
    CloseConnection {
        initial_timestamp: String,
        final_timestamp: String,
    },
    Invalid(String),
}


// The Implementation for the RequestType Enum
impl RequestType{
    fn from_message_string(message_string: &str, pool: Arc<Pool>) -> RequestType {
        println!("Checking request type...");

I can define methods using enums, which is most similar to what I assume is a class. In what scenario would you use a struct?


Solution

  • A struct is similar to a JavaScript object, except that it has a fixed set of fields and each field has a type. In order to construct an instance of the struct, you must provide all fields. Your StartListen struct has two fields, and you need a SocketAddr and a TcpListener to construct it.

    An enum doesn't have an analogy in JavaScript. Instead of having fields, an enum has variants. In order to construct an instance of an enum, you must provide exactly one variant. The variant itself might require data, like a struct, and all fields of the variant must be provided to construct it. Your RequestType enum has three variants, and an instance of RequestType must be one of RequestWork, CloseConnection or Invalid.

    • You can think of a struct as an aggregate of things.
    • You can think of an enum as a choice from a selection of mutually exclusive alternatives. These alternatives may carry data too.