Precautions
Although the generic types provided by the framework significantly enhance development convenience, they should be used with caution for business models (not abused), as generic types can obscure the actual data types. This can be more detrimental than beneficial for long-term maintenance in business projects, especially complex ones. The data types of a business model should be as clear, meaningful, and immutable as possible to facilitate type checking and optimization during the compilation stage, and to benefit long-term maintenance.
For example, here is a real business model case provided by an enthusiastic community member:
type MiDispatchData struct {
Status *g.Var `json:"status"`
BrandId *g.Var `json:"brand_id"`
AreaId *g.Var `json:"area_id"`
Year *g.Var `json:"year"`
Month *g.Var `json:"month"`
Day *g.Var `json:"day"`
Hour *g.Var `json:"hour"`
RequestTime *g.Var `json:"request_time"`
Source *g.Var `json:"source"`
BikeId *g.Var `json:"bike_id"`
BikeType *g.Var `json:"bike_type"`
Lon *g.Var `json:"lon"`
Lat *g.Var `json:"lat"`
SiteId *g.Var `json:"site_id"`
BikeMac *g.Var `json:"bike_mac"`
}
While this approach allows the program to run normally and covers business scenarios, it loses the compiler advantage of compiled languages (similar to PHP variables), making it difficult to determine the data type of fields during later project maintenance.
Recommendations
- Generics are more frequently used in foundational components and middleware projects.
- If a field has multiple meanings or types in a business scenario, generics can be used instead of types like
interface{}
.