cuelang.org/go@v0.10.1/cue/examplecompile_test.go (about)

     1  // Copyright 2021 CUE Authors
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package cue_test
    16  
    17  import (
    18  	"fmt"
    19  	"log"
    20  
    21  	"cuelang.org/go/cue"
    22  	"cuelang.org/go/cue/cuecontext"
    23  )
    24  
    25  func ExampleContext() {
    26  	ctx := cuecontext.New()
    27  
    28  	v := ctx.CompileString(`
    29  		a: 2
    30  		b: 3
    31  		"a+b": a + b
    32  	`)
    33  	if err := v.Err(); err != nil {
    34  		log.Fatal(err)
    35  	}
    36  
    37  	p("lookups")
    38  	p("a:     %v", v.LookupPath(cue.ParsePath("a")))
    39  	p("b:     %v", v.LookupPath(cue.ParsePath("b")))
    40  	p(`"a+b": %v`, v.LookupPath(cue.ParsePath(`"a+b"`)))
    41  	p("")
    42  	p("expressions")
    43  	p("a + b: %v", ctx.CompileString("a + b", cue.Scope(v)))
    44  	p("a * b: %v", ctx.CompileString("a * b", cue.Scope(v)))
    45  
    46  	// Output:
    47  	// lookups
    48  	// a:     2
    49  	// b:     3
    50  	// "a+b": 5
    51  	//
    52  	// expressions
    53  	// a + b: 5
    54  	// a * b: 6
    55  }
    56  
    57  func p(format string, args ...interface{}) {
    58  	fmt.Printf(format+"\n", args...)
    59  }