如何判定泛型类型

在一个泛型函数中, 如何判定入参的实际类型

pub fn floorFnEx[T, M](
  number : T,
  significance : M
) -> Result[Double, @common.ErrorType] {

如何判定number的实际类型,
如果是Double, 直接使用,
是String,try_parse
是Bool, 转为1或0
其他, 输出错误

现在的做法是自定义了一组枚举, 用法如下

let num = match number {
    @common.ValueType::Number(n) => n
    @common.ValueType::Bool(b) => 
      match b {
        true => 1.0
        false => 0.0
      }
    @common.ValueType::String(s) => {
      let n = @strconv.parse_double?(s)
      if n.is_ok() {
        n.unwrap()
      } else {
        return Err(@common.ErrorType::ValueError)
      }
    }
    _ => return Err(@common.ErrorType::ValueError)
  }

但是感觉有点繁琐, 使用泛型更清晰简单些

可以用trait

trait ToDouble {
  fn to_double(Self) -> Result[Double, @common.ErrorType]
}

impl ToDouble for String with to_double(self) {
  @strconv.parse_double(self).or_error(...)
}

impl ToDouble for Double with to_double(self) {
  Ok(self)
}

impl ToDouble for Bool with to_double(self) {
  ...
}

pub fn floorFnEx[T: ToDouble, M](
  number : T,
  significance : M
) -> Result[Double, @common.ErrorType] {
  ...
  guard let Ok(n) = number.to_double() else {
    x -> x
  }
  ...
}

对于没impl ToDouble的类型,直接编译期报错。如果希望运行期才报错,可以加一个ToDouble trait的默认实现(具体怎么写我忘了,官方文档上有)