Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
jpluscplusm opened this issue Mar 25, 2024 · 0 comments
Open
Labels
content idea Idea for a new piece of content triage Triage required by the CUE team

Comments

@jpluscplusm
Copy link
Collaborator

From cue-lang/cue#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
@jpluscplusm jpluscplusm added content idea Idea for a new piece of content triage Triage required by the CUE team labels Mar 25, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
content idea Idea for a new piece of content triage Triage required by the CUE team
Projects
Status: Backlog
Development

No branches or pull requests

1 participant