You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何创建带验证的泛型负数结构体?解决内联私有函数冲突

实现带验证的泛型负数结构体

我需要实现一个泛型负数包装类型,选择结构体(Struct)作为载体,但遇到了几个问题:

  • 结构体不允许包含do绑定,没法在构造函数内直接做验证(报错:This construct is deprecated: Structs cannot contain 'do' bindings because the default constructor for structs would not execute these bindings)
  • 把验证逻辑移到公开构造函数后,出现类型约束错误:This construct causes code to be less generic than indicated by the type annotations. The type variable 'a has been constrained to be type 'IComparable'. Type constraint mismatch when applying the default type 'IComparable' for a type inference variable. The type 'IComparable' does not support the operator 'get_Zero' Consider adding further type constraints.
  • 尝试用inline new构造函数,编译器不支持这种写法
  • 尝试在类型上写static member inline Create或模块内let inline create函数,但构造函数设为私有会触发报错:[FS1113] The value 'create' was marked inline but its implementation makes use of an internal or private function which is not sufficiently accessible

需要实现满足以下条件的包装类型:

  • 是结构体(Struct)
  • 支持泛型数值类型
  • 构造时始终执行验证

解决方案

核心思路是将结构体的构造函数设为internal(而非private),同时在配套模块中提供inline的创建函数来处理验证逻辑。这样既保证了外部无法直接构造无效实例,又能通过inline函数保留泛型数值类型的约束支持。

代码实现

module NegativeModule =
    [<Struct>]
    type Negative<'T> internal (x: 'T) =
        member _.Value = x

    let inline create (x: ^a) =
        if x >= LanguagePrimitives.GenericZero then
            failwithf $"Value must be < 0: {x}"
        Negative<'a> x

关键细节说明

  1. 构造函数权限:结构体Negative<'T>的构造函数标记为internal,确保只有同一程序集内的代码可以直接调用,外部无法绕过验证创建实例。
  2. 验证逻辑:模块内的inline create函数负责验证,通过LanguagePrimitives.GenericZero获取泛型零值,对比输入值是否非负,验证失败则抛出异常。
  3. 泛型兼容性:inline关键字让函数能适配所有支持比较运算和零值的数值类型(如int、float、decimal等),保留泛型的灵活性。
  4. 实例创建入口:外部代码只能通过NegativeModule.create来创建Negative实例,确保验证逻辑一定会被执行。

测试示例

// 合法:创建负数实例
let validNegative = NegativeModule.create -5
printfn "%d" validNegative.Value // 输出 -5

// 非法:传入非负数,触发异常
let invalidNegative = NegativeModule.create 3 // 抛出异常:Value must be < 0: 3

内容的提问来源于stack exchange,提问作者capitalistcuttle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 12:35:06