F# - 结构类型

F# - 结构类型 首页 / F#入门教程 / F# - 结构类型

F#中的结构(Struct)是值数据类型,它可以帮助您制作一个变量,保存各种数据类型的相关数据, struct 关键字用于创建结构。

语法

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

有两种语法,通常使用第一种语法,因为如果使用 struct end 关键字,则可以省略 StructAttribute 属性。

与类(class)不同,结构(struct)不能被继承并且不能包含let或do绑定,您必须使用 val 关键字在结构中声明字段。

使用 val 关键字定义字段及其类型时,无法初始化字段值,而是将它们初始化为零或null。因此,对于具有隐式构造函数的结构, val 声明使用 DefaultValue 属性进行注释。

下面的程序创建一个线结构以及一个构造函数。程序使用以下结构计算线的长度-

链接:https://www.learnfk.comhttps://www.learnfk.com/fsharp/fsharp-structures.html

来源:LearnFk无涯教程网

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

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

重学前端 -〔程劭非(winter)〕

软件工程之美 -〔宝玉〕

许式伟的架构课 -〔许式伟〕

黄勇的OKR实战笔记 -〔黄勇〕

后端技术面试 38 讲 -〔李智慧〕

Vim 实用技巧必知必会 -〔吴咏炜〕

成为AI产品经理 -〔刘海丰〕

程序员的测试课 -〔郑晔〕

Vue 3 企业级项目实战课 -〔杨文坚〕

好记忆不如烂笔头。留下您的足迹吧 :)