在进行作业时是否可以在F#中强制记录类型?

Tom*_*son 3 f#

为了解释我认为最好用一个例子:

type myRec = {x: string}
type myRec2 = {x: string}
let x = {x = "hello"}
let y(a: myRec) = a.x
y(x);;

  y(x);;
   --^

error FS0001: This expression was expected to have type
    myRec    
but here has type
    myRec2
Run Code Online (Sandbox Code Playgroud)

所以,我怎么用力x,以有型myRec,如果两者myRecmyRec2具有相同的签名?

ild*_*arn 11

let x = { myRec.x = "hello" }
// or
let x:myRec = { x = "hello" }
// or
let x = { x = "hello" } : myRec
Run Code Online (Sandbox Code Playgroud)

文档中提供了更多详细信息和示例.

编辑:注释的备选方案.

  • 我还发现我可以写:`let x:myRec = {x ="hello"}`,我认为这是最可读的. (3认同)
  • 为了完整起见,让我添加`let x = {x ="hello"}:myRec`. (2认同)