F# - 結構體



F# 中的結構體是一種值型別資料型別。它可以幫助您使用單個變數來儲存各種資料型別的相關資料。struct 關鍵字用於建立結構體。

語法

定義結構體的語法如下:

[ attributes ]
type [accessibility-modifier] type-name =
   struct
      type-definition-elements
   end
// or
[ attributes ]
[<StructAttribute>]
type [accessibility-modifier] type-name =
   type-definition-elements

有兩種語法。第一種語法最常用,因為如果您使用structend 關鍵字,則可以省略StructAttribute 屬性。

結構體定義元素提供:

  • 成員宣告和定義。
  • 建構函式以及可變和不可變欄位。
  • 成員和介面實現。

與類不同,結構體不能被繼承,也不能包含 let 或 do 繫結。由於結構體沒有 let 繫結,因此必須使用val 關鍵字在結構體中宣告欄位。

當您使用val 關鍵字定義欄位及其型別時,不能初始化欄位值,而是將其初始化為零或 null。因此,對於具有隱式建構函式的結構體,val 宣告必須使用DefaultValue 屬性進行註釋。

示例

以下程式建立一個線段結構體以及一個建構函式。程式使用該結構體計算線段的長度:

type Line = struct
   val X1 : float
   val Y1 : float
   val X2 : float
   val Y2 : float

   new (x1, y1, x2, y2) =
      {X1 = x1; Y1 = y1; X2 = x2; Y2 = y2;}
end
let calcLength(a : Line)=
   let sqr a = a * a
   sqrt(sqr(a.X1 - a.X2) + sqr(a.Y1 - a.Y2) )

let aLine = new Line(1.0, 1.0, 4.0, 5.0)
let length = calcLength aLine
printfn "Length of the Line: %g " length

編譯並執行程式後,將輸出以下內容:

Length of the Line: 5
廣告

© . All rights reserved.