gpt4 book ai didi

f# - F# 中的强类型 ID?

转载 作者:行者123 更新时间:2023-12-05 00:41:14 27 4
gpt4 key购买 nike

我的应用程序中有两种实体:客户和产品。它们每个都在数据库级别由 UUID 标识。

在我的 F# 代码中,这可以表示为 System.Guid .

为了可读性,我添加了一些这样的类型:

open System

type CustomerId = Guid

type ProductId = Guid

但是,这并不妨碍我使用 ProductId作为 CustomerId反之亦然。

我想出了一个包装器的想法来防止这种情况:
open System

[<Struct>]
type ProductId =
{
Product : Guid
}

[<Struct>]
type CustomerId =
{
Customer : Guid
}

这使得初始化更加冗长,而且可能不那么直观:
let productId = { Product = Guid.NewGuid () }

但它增加了类型安全性:
// let customerId : CustomerId = productId // Type error

我想知道还有哪些其他方法。

最佳答案

您可以使用 single-case union类型:

open System

[<Struct>]
type ProductId = ProductId of Guid

[<Struct>]
type CustomerId = CustomerId of Guid

let productId = ProductId (Guid.NewGuid())

通常我们会直接向类型添加一些方便的辅助方法/属性:
[<Struct>]
type ProductId = private ProductId of Guid with
static member Create () = ProductId (Guid.NewGuid())
member this.Value = let (ProductId i) = this in i

[<Struct>]
type CustomerId = private CustomerId of Guid with
static member Create () = CustomerId (Guid.NewGuid())
member this.Value = let (CustomerId i) = this in i

let productId = ProductId.Create ()
productId.Value |> printfn "%A"

关于f# - F# 中的强类型 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56235474/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com