Skip to content

Primitives

The CDDL language supports some primitives as type constraints. These primitives - uint, int, bytes, bstr, text/tstr are directly translated to Go type declarations.

From the definition file primitives.cddl containing the following content,

primitives.cddl
1
2
3
4
name = tstr
age = uint
public-key = bytes
account-balance = int

go code can be generated by invoking

cddlc generate --source primitives.cddl --out lib/primitives.go --package foo

This generates the declarations and validation methods. Since the types are directly enforced by the Go type checker, the Valid() methods return nil by default. All values are public by default with identifiers formatted as PascalCase.

primitives.go
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/*
  File generated using `cddlc.exe gen`. DO NOT EDIT
*/

package foo

// (cddlc) Ident: name
type Name string

// Valid evaluates type constraints on name and returns nil if valid 
// else it returns a list of validation errors
func (name *Name) Valid() error {
    return nil
}

// (cddlc) Ident: age
type Age uint

// Valid evaluates type constraints on age and returns nil if valid 
// else it returns a list of validation errors
func (age *Age) Valid() error {
    return nil
}

// (cddlc) Ident: public-key
type PublicKey []byte

// Valid evaluates type constraints on public-key and returns nil if valid 
// else it returns a list of validation errors
func (public-key *PublicKey) Valid() error {
    return nil
}

// (cddlc) Ident: account-balance
type AccountBalance int

// Valid evaluates type constraints on account-balance and returns nil if valid 
// else it returns a list of validation errors
func (account-balance *AccountBalance) Valid() error {
    return nil
}