cue-lang / docs-and-content

A place to discuss, plan, and track documentation on cuelang.org
5 stars 1 forks source link

docs/???/???: Walking cue.Value with optional fields with the Go API #112

Open jpluscplusm opened 3 months ago

jpluscplusm commented 3 months ago

From https://github.com/cue-lang/cue/discussions/2783:

Question:

I'm looking to use the golang library to implement a function that walks the structure and grabs all fields regardless of the field constraints, as in first!:, second: and third?:, so far I don't have issues with first and second but I've not been able to get third unless it's been given a value.

Solution:

go mod tidy
go run .
cmp stdout stdout.golden

-- go.mod --
module mod.com

go 1.21.4

require cuelang.org/go v0.7.0
-- main.go --
package main

import (
    "fmt"
    "log"

    "cuelang.org/go/cue"
    "cuelang.org/go/cue/cuecontext"
)

const src = `
x?: string
y!: string
z: string
`

func main() {
    ctx := cuecontext.New()
    v := ctx.CompileString(src)
    fields, err := v.Fields(
        cue.Optional(true),
        cue.Hidden(true),
        cue.Definitions(true),
    )
    if err != nil {
        log.Fatal(err)
    }
    for fields.Next() {
        fmt.Printf("found field %v\n", fields.Selector())
    }
}
-- stdout.golden --
found field x?
found field y!
found field z