The CUE Context



Working with CUE from Go starts with cue.Context. Code is compiled and values are built using a context. You will see the basic methods for cue.Context here and later pages will increase the sophistication.

When working with multiple values, they should come from the same runtime. This requirement will be removed in a future version.

Compiling with Context

This is the simplest program to print a CUE value. It will print the first error message if you have one.

context.go

package main

import (
	"fmt"

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

const val = `
i: int
s: "hello"
`

func main() {
	var (
		c *cue.Context
		v cue.Value
	)

	// create a context
	c = cuecontext.New()

	// compile some CUE into a Value
	v = c.CompileString(val)

	// print the value
	fmt.Println(v)
}

go run context.go

{
	i: int
	s: "hello"
}

Compiling with a Scope

If you have schemas in one string and values in another, you can use the cue.Scope option to provide a “context” for the cue.Context.

scope.go

package main

import (
	"fmt"

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

const schema = `
#schema: {
	i: int
	s: string
}
`

const val = `
v: #schema & {
	i: 1
	s: "hello"
}
`

func main() {
	var (
		c *cue.Context
		s cue.Value
		v cue.Value
	)

	// create a context
	c = cuecontext.New()

	// compile our schema first
	s = c.CompileString(schema)

	// compile our value with scope
	v = c.CompileString(val, cue.Scope(s))

	// print the value
	fmt.Println(v)
}

go run scope.go

{
	v: {
		i: 1
		s: "hello"
	}
}

Encoding Values from Go

You can also transform your Go types and values into CUE values. We can control the output with struct tags. Note that

  • Only public members will be encoded by CUE.
  • We can use omitempty to prevent output, but this impacts the type encoding as well.
  • Numerical types have some quirks we’ll talk about later. CUE normally uses math/big types.
  • Details can be found in the pkg.go.dev cue.Context.Encode docs.

encoding.go

package main

import (
	"fmt"

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

type Val struct {
	I int    `json:"i"`
	S string `json:"s,omitempty"`
	b bool
}

func main() {
	var (
		c *cue.Context
		v cue.Value
	)

	val := Val{
		I: 1,
		S: "hello",
		b: true,
	}

	// create a context
	c = cuecontext.New()

	// compile some CUE into a Value
	v = c.Encode(val)

	// print the value
	fmt.Println(v)

	// we can also encode types
	t := c.EncodeType(Val{})
	fmt.Println(t)
}

go run encoding.go

{
	i: 1
	s: "hello"
}
{
	i: int64
}
We'll never share your email with anyone else.
2024 Hofstadter, Inc