乐闻世界logo
搜索文章和话题

What is the difference between a struct and an enum in Rust?

1个答案

1

In the Rust programming language, struct (structs) and enum (enums) are both tools for defining data types, but they have distinct characteristics and uses.

struct (structs)

Structs are primarily used to combine multiple related data into a composite type. Each field has a name and type, allowing explicit access. Structs are ideal for modeling concrete entities and their attributes.

Example:

rust
struct Person { name: String, age: u32, }

In this example, the Person struct represents a person, including their name and age.

enum (enums)

Enums are used to define types that can take on one of several different values. Each enum variant can carry data of varying types and quantities. Enums are ideal for handling values of different kinds that are related.

Example:

rust
enum WebEvent { PageLoad, PageUnload, KeyPress(char), Paste(String), Click { x: i64, y: i64 }, }

In this example, the WebEvent enum includes several different web events, such as page load and unload, key press events, paste events, and click events. Each event may associate with data of different types.

Summary

Overall, struct is suitable for defining concrete entities with explicit attributes, while enum is ideal for defining a set of possible variable values that can be of different types or combinations. In actual development, choosing between struct and enum depends on how you need to express your data.

2024年8月7日 14:13 回复

你的答案