标准库



CUE 有包含许多辅助 package 的标准库。

概览

CUE 文档首页

大体分为两种类型:

  1. 一些只能在 pure.cue 中使用的封闭函数
  2. 一些与外界交互的非封闭函数,它们为 _tool.cue 文件的脚本层提供一些函数
Pure Packages
  • crypto/...: Hash calculations
  • encoding/...: To / from [base64, csv, hex, json, yaml]
  • html: For (un)escaping HTML strings
  • list: For working with lists
  • math: Extra advanced functions
  • net: Constraints for network related values
  • path: Work with filepaths with OS awareness
  • regexp: More advanced regexp functions
  • strconv: Format and parse numbers, quote and unquote runes
  • strings: Advanced helpers for working with strings
  • struct: Set min and max fields allowed
  • text/tabwriter: Write tabular data
  • text/template: Advanced string templates
  • time: Format, parse, and constraint times and durations
Tool Packages
  • tool/cli: Work with stdio
  • tool/exec: Run external commands
  • tool/file: List, read, and write files
  • tool/http: Make http requests
  • tool/os: work with environment vars

示例

Encoding

encoding.cue

package stdlib

import (
	"encoding/json"
)

data: """
	{
		"hello": "world",
		"list": [ 1, 2 ],
		"nested": {
			"foo": "bar"
		}
	}
	"""

jval: json.Unmarshal(data)

val: {
	hello: "world"
	list: [1, 2]
	nested: foo: "bar"
}

cjson: json.Marshal(val)
Strings

strings.cue

package stdlib

import "strings"

s: "HelloWorld"

u: strings.ToUpper(s)
l: strings.ToLower(s)

line:  "Cue stands for configure, unify, execute"
words: strings.Split(line, " ")
lined: strings.Join(words, " ")

haspre: strings.HasPrefix(line, "Cue")
index:  strings.Index(line, "unify")
List

list.cue

package stdlib

import "list"

l1: [1, 2, 3, 4, 5]
l2: ["c", "b", "a"]

// constrain length
l2: list.MinItems(1)
l2: list.MaxItems(3)

// slice a list
l3: list.Slice(l1, 2, 4)

// get the sum and product
sum: list.Sum(l1)
prd: list.Product(l1)

// linear search for list (no binary)
lc: list.Contains(l1, 2)

// sort a list
ls:  list.Sort(l2, list.Ascending)
l2s: list.IsSorted(l2, list.Ascending)
lss: list.IsSorted(ls, list.Ascending)

// Flatten a list
ll: [1, [2, 3], [4, [5]]]
lf: list.FlattenN(ll, 1)

Constrain

constrain.cue

package stdlib

import (
	"net"
	"time"
)

// string with ip format
ip: net.IPv4
ip: "10.1.2.3"

// string with time format
ts: time.Format(time.ANSIC)
ts: "Mon Jan 2 15:04:05 2006"
我们绝不会将你的邮箱分享给任何人。
2024 Hofstadter, Inc