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.
, :
struct UnitStruct;
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);
handle_error(ErrorCode::BadHTTPCode(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,
BadRequest,
NotFound,
}