package main
import (
"fmt""os""cuelang.org/go/cue""cuelang.org/go/cue/cuecontext")
funcmain() {
c := cuecontext.New()
// read and compile value
d, _ := os.ReadFile("value.cue")
val := c.CompileBytes(d)
paths := []string{
"a",
"a.e",
"d.g",
"l",
"b",
"x.y",
}
for _, path :=range paths {
v := val.LookupPath(cue.ParsePath(path))
k := v.Kind()
i := v.IncompleteKind()
fmt.Printf("%q %v %v %v\n", path, k, i, v)
}
}
go run kind.go
"a" struct struct {
b: "b"
c: "c"
e: int
}
"a.e" _|_ int int
"d.g" _|_ _ _
"l" list list [1, 2, "y", "z"]
"b" bytes bytes 'abc123'
"x.y" _|_ _|_ _|_ // field "x" not found
Value 类型有一些函数可以把抽象类型转换为 Go 底层类型。
你应该首先确认 Value 的类型,再尝试转换。
conversions.go
package main
import (
"fmt""os""cuelang.org/go/cue""cuelang.org/go/cue/cuecontext")
funcmain() {
c := cuecontext.New()
// read and compile value
d, _ := os.ReadFile("value.cue")
val := c.CompileBytes(d)
var (
s string b []byte i int64 f float64 )
// read into Go basic types
s, _ = val.LookupPath(cue.ParsePath("a.b")).String()
b, _ = val.LookupPath(cue.ParsePath("b")).Bytes()
i, _ = val.LookupPath(cue.ParsePath("d.e")).Int64()
f, _ = val.LookupPath(cue.ParsePath("d.f")).Float64()
fmt.Println(s, b, i, f)
// an error
s, err := val.LookupPath(cue.ParsePath("a.e")).String()
if err !=nil {
fmt.Println(err)
}
}
go run conversions.go
b [97 98 99 49 50 51] 42 3.14
a.e: cannot use value int (type int) as string
Len
Len 返回一个list的长度以及一个 bytes 里的字节数。
length.go
package main
import (
"fmt""os""cuelang.org/go/cue""cuelang.org/go/cue/cuecontext")
funcmain() {
c := cuecontext.New()
// read and compile value
d, _ := os.ReadFile("value.cue")
val := c.CompileBytes(d)
paths := []string{
"a",
"d.e",
"d.g",
"l",
"b",
}
for _, path :=range paths {
fmt.Printf("==== %s ====\n", path)
v := val.LookupPath(cue.ParsePath(path))
p := v.Path()
k := v.IncompleteKind()
l := v.Len()
fmt.Printf("%q %v %v\n%# v\n", p, k, l, v)
}
}
go run length.go
==== a ====
"a" struct _|_ // len not supported for type struct
b: "b"
c: "c"
e: int
==== d.g ====
"d.g" _ _|_ // len not supported for type _|_
_
==== l ====
"l" list 4
[1, 2, "y", "z"]
==== b ====
"b" bytes 6
'abc123'