Flux数据类型基础
Flux 数据类型定义了一组可能的值和操作(function 类型)。 Flux 是静态类型的,数据类型不用显式声明,并且类型是从变量的使用方式推断出来的。
1、基本数据类型
Boolean 布尔(true、false)
Bytes 字节 (bytes)
Duration 持续时间类型
比如range函数使用的:
1ns
1h
1w
3d12h4m25s
Regular expression 正则表达式类型
/^[a-z0-9]+$/
String 字符串
Time 时间类型
2021-01-01
2021-01-01T00:00:00Z
2021-01-01T00:00:00.000Z
Float 64位浮点数(IEEE 754-2019)
0.0
123.4
-123.456
Integer (64位整数)
0
2
1254
-1254
UIntegers (无符号整数)
uint(v: 123)
Null (表示缺失或者未知的值)
2、复合数据类型
Flux 复合类型是从基本类型构造的类型
记录类型 record
记录类型是一组键值对。
{foo: "bar", baz: 123.4, quz: -2}
{"Company Name": "ACME", "Street Address": "123 Main St.", id: 1123445}
获取记录值:
c = {name: "John Doe", address: "123 Main St.", id: 1123445}
c.name
// Returns John Doe
c.id
// Returns 1123445
或者:
c = {"Company Name": "ACME", "Street Address": "123 Main St.", id: 1123445}
c["Company Name"]
// Returns ACME
c["id"]
// Returns 1123445
获取嵌套记录的值:
customer =
{
name: "John Doe",
address: {
street: "123 Main St.",
city: "Pleasantville",
state: "New York"
}
}
customer.address.street
// Returns 123 Main St.
customer["address"]["city"]
// Returns Pleasantville
customer["address"].state
// Returns New York
记录(record)的操作
扩展记录
使用 with 运算符来扩展记录。 如果指定的键存在,with 运算符将覆盖记录属性,如果键不存在,则添加新的属性。
c = {name: "John Doe", id: 1123445}
{c with spouse: "Jane Doe", pet: "Spot"}
// Returns {id: 1123445, name: John Doe, pet: Spot, spouse: Jane Doe}
列出记录中的键
导入 experimental 包。
experimental.objectKeys 返回记录中的键数组。
import "experimental"
c = {name: "John Doe", id: 1123445}
experimental.objectKeys(o: c)
// Returns [name, id]
数组 array
数组类型是相同类型值的有序序列
["1st", "2nd", "3rd"]
[1.23, 4.56, 7.89]
[10, 25, -15]
字典 dictionary
字典类型是具有相同类型的键和相同类型的值的键值对的集合。
[0: "Sun", 1: "Mon", 2: "Tue"]
["red": "#FF0000", "green": "#00FF00", "blue": "#0000FF"]
[1.0: {stable: 12, latest: 12}, 1.1: {stable: 3, latest: 15}]
字典操作:
1)获取值,需要导入import “dict”
import "dict"
positions =
[
"Manager": "Jane Doe",
"Asst. Manager": "Jack Smith",
"Clerk": "John Doe",
]
dict.get(dict: positions, key: "Manager", default: "Unknown position")
// Returns Jane Doe
dict.get(dict: positions, key: "Teller", default: "Unknown position")
// Returns Unknown position
函数 function
函数类型是一组执行操作的参数。
() => 1
(a, b) => a + b
(a, b, c=2) => {
d = a + b
return d / c
}
functionName = (functionParameters) => functionBody
例子1:
square = (n) => n * n
square(n:3)
// Returns 9
例子2:
multiply = (x, y) => x * y
multiply(x: 2, y: 15)
// Returns 30
带默认参数的例子:
pow = (n, p=10) => n ^ p
pow(n: 2)
// Returns 1024
例子:
// Function that returns the value 1
() => 1
// Function that returns the sum of a and b
(a, b) => a + b
// Function with default values
(x=1, y=1) => x * y
// Function with a block body
(a, b, c) => {
d = a + b
return d / c
}