When should we use structure rather than enumeration?

Structures and enumerations are similar to each other.

When would it be better to use a structure rather than an enumeration (or vice versa)? Can someone give a clear example where using a structure is preferable to using an enumeration?

+5
source share
3 answers

Perhaps the easiest way to explain the fundamental difference is that an enumeration contains “options” of which you can only have one at a time, while a structure contains one or more fields, all of which you must have.

So you can use enumsomething like an error code to simulate, where you can only have one code at a time:

enum ErrorCode {
    NoDataReceived,
    CorruptedData,
    BadResponse,
}

Enum . , ErrorCode :

enum ErrorCode {
    NoDataReceived,
    CorruptedData,
    BadResponse,
    BadHTTPCode(u16),
}

ErrorCode::BadHTTPCode u16.

, :

// Unit structs have no fields
struct UnitStruct;

// Tuple structs contain anonymous values.
struct TupleStruct(u16, &'static str);

, ErrorCode ErrorCode, ErrorCode ( ).

fn handle_error(error: ErrorCode) {
    match error {
        ErrorCode::NoDataReceived => println!("No data received."),
        ErrorCode::CorruptedData => println!("Data corrupted."),
        ErrorCode::BadResponse => println!("Bad response received from server."),
        ErrorCode::BadHTTPCode(code) => println!("Bad HTTP code received: {}", code)
    };
}

fn main() {
    handle_error(ErrorCode::NoDataReceived); // prints "No data received."
    handle_error(ErrorCode::BadHTTPCode(404)); // prints "Bad HTTP code received: 404"
}

match , , , , .


, , , - , , "".

struct Response {
    data: Option<Data>,
    response: HTTPResponse,
    error: String,
}

fn main() {
    let response = Response {
        data: Option::None,
        response: HTTPResponse::BadRequest,
        error: "Bad request".to_owned()
    }
}

, Response .

, response (. HTTPResponse::Something) , HTTPResponse . :

enum HTTPResponse {
    Ok,         // 200
    BadRequest, // 400
    NotFound,   // 404
}
+4

. "" , . , struct , . , struct. , . , , - . , , . , , () , . , .

, , struct. , , , , .

+2

An Enumis a type with a limited set of values.

enum Rainbow {
    Red,
    Orange,
    Yellow,
    Green,
    Blue,
    Indigo,
    Violet
}

let color = Red;

match color {
    Red => { handle Red case },
    // all the rest would go here
}

You can store data in Enum if you need it.

enum ParseData {
    Whitespace,
    Token(String),
    Number(i32),
}

fn parse(input: String) -> Result<String, ParseData>;

Structure is a way of representing things.

struct Window {
    title: String,
    position: Position,
    visible: boolean,
}

Now you can create new objects Windowthat represent a window on your screen.

0
source

Source: https://habr.com/ru/post/1693501/


All Articles