pub trait DataTypeOf {
const DATA_TYPE: DataType;
}Expand description
Marker trait for mapping concrete Rust types to DataType
Provides an associated constant to know the corresponding DataType at compile time,
facilitating static type-to-data-type queries in generic code based on T.
This trait enables compile-time type-to-data-type mapping, allowing generic code
to determine the appropriate DataType for any type that implements this trait.
This is particularly useful for serialization frameworks, validation systems,
and other scenarios where you need to know the data type at compile time.
§Usage
The trait is automatically implemented for all basic Rust types and common
third-party types. You can use it in generic functions to determine the
corresponding DataType for any type.
§Examples
§Basic Usage
use qubit_common::lang::{DataType, DataTypeOf};
// Get the data type for a specific type
assert_eq!(i32::DATA_TYPE, DataType::Int32);
assert_eq!(String::DATA_TYPE, DataType::String);
assert_eq!(bool::DATA_TYPE, DataType::Bool);§Generic Function Example
use qubit_common::lang::{DataType, DataTypeOf};
fn get_type_name<T: DataTypeOf>() -> &'static str {
T::DATA_TYPE.as_str()
}
assert_eq!(get_type_name::<i32>(), "int32");
assert_eq!(get_type_name::<String>(), "string");
assert_eq!(get_type_name::<f64>(), "float64");§Generic Value Container Example
use qubit_common::lang::{DataType, DataTypeOf};
struct TypedValue<T: DataTypeOf> {
value: T,
data_type: DataType,
}
impl<T: DataTypeOf> TypedValue<T> {
fn new(value: T) -> Self {
Self {
value,
data_type: T::DATA_TYPE,
}
}
fn get_data_type(&self) -> DataType {
self.data_type
}
}
let typed_value = TypedValue::new(42i32);
assert_eq!(typed_value.get_data_type(), DataType::Int32);§Type Validation Example
use qubit_common::lang::{DataType, DataTypeOf};
fn validate_numeric_type<T: DataTypeOf>() -> bool {
matches!(T::DATA_TYPE,
DataType::Int8 | DataType::Int16 | DataType::Int32 | DataType::Int64 | DataType::Int128 |
DataType::UInt8 | DataType::UInt16 | DataType::UInt32 | DataType::UInt64 | DataType::UInt128 |
DataType::Float32 | DataType::Float64 | DataType::BigInteger | DataType::BigDecimal
)
}
assert!(validate_numeric_type::<i32>());
assert!(validate_numeric_type::<f64>());
assert!(!validate_numeric_type::<String>());§Supported Types
The following types have DataTypeOf implementations:
- Basic Types:
bool,char,i8,i16,i32,i64,i128,u8,u16,u32,u64,u128,f32,f64 - String Types:
String - Date/Time Types:
NaiveDate,NaiveTime,NaiveDateTime,DateTime<Utc> - Big Number Types:
BigInt,BigDecimal
§Author
Haixing Hu
Required Associated Constants§
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.