When working with GORM in Go, implementing enumeration typically involves several approaches. GORM does not natively support enum types because Go itself lacks native enum support, but we can simulate enum functionality using certain strategies. Here are some common methods:
Method One: Using Custom Types
- Define a custom type: First, define a custom type based on
stringorintto represent the enumeration values. - Add methods to the type: Implement methods for this type to ensure valid assignments.
- Use the custom type in GORM models: Apply this custom enum type as the field type in your GORM models.
Example
Suppose we want to define a 'role' enumeration for users, with values 'Admin' and 'Member'.
gopackage main import ( "gorm.io/gorm" "log" ) // Define custom type // ... (code remains the same)
In this example, we define a Role type where the values Admin and Member are represented as Role types. We use Role as the field type in the User model. The Scan and Value methods ensure GORM correctly handles reading and writing this type.
Method Two: Using Constants and Validation
- Define constants: Declare a set of constants representing the enumeration values.
- Add a field to the model: Include a standard
stringorintfield to store the enumeration value. - Add validation logic: Validate the field value is a valid enumeration value before insertion or update.
Example
Continuing with the role example, we directly use string without defining a new type:
gopackage main import ( "gorm.io/gorm" "log" ) const ( RoleAdmin = "Admin" RoleMember = "Member" ) // Define model // ... (code remains the same)
Here, we must manually validate the Role field value in the code to ensure it matches one of the valid enumeration values.
Summary
Although Go and GORM lack native enum support, the above methods effectively implement similar enumeration functionality in GORM, ensuring data validity and integrity. The choice depends on specific use cases and personal preference.