关于CUE中定义数组并导出为OpenAPI时出现不完整值错误的咨询
Great question! This boils down to how CUE's array constraints interact with OpenAPI schema generation rules, especially when using cue export --out openapi. Let's break this down clearly:
1. The unique behavior of CUE array constraints
Your definition 2 * [string] creates a fixed-length array requirement: the array must have exactly 2 string elements. But in CUE, a bare string is an incomplete value (it doesn't have a concrete string instance). When exporting to OpenAPI, CUE tries to generate a valid default value for this array—but since string has no inherent default, it throws that "incomplete value" error.
Compare this to the object property id: int: while int is also incomplete, OpenAPI doesn't require object properties to have a default value. CUE recognizes this, so it doesn't force a default for object fields, hence no error there.
2. OpenAPI's rules for array defaults
OpenAPI requires that if you provide a default for an array, it must be a complete, valid array instance with concrete values. When you use 2 * [string], CUE tries to generate a default array of length 2—but each element is just the incomplete string type, which can't form a valid default. This is why you get those errors.
When you switch to string | *null, you're giving CUE an explicit default value (null) for each array element. Now it can generate a valid default array ([null, null]) that satisfies OpenAPI's requirements, so the export works.
3. Workarounds if you don't want default values
You don't have to add *null to make this work. Here are two better alternatives:
- Use
--no-defaultsduring export: Runcue export --out openapi --no-defaults test.cueinstead. This tells CUE not to generate any default values at all, so it won't try to fill in those incomplete array elements. - Adjust your CUE array syntax: Instead of
2 * [string], write[string, string]. This still enforces a 2-element string array, but CUE is less aggressive about generating a default for this form (though--no-defaultsis still more reliable if you want to avoid defaults entirely).
Example with --no-defaults
Keep your original CUE code:
#match: { id: int teams: 2 * [string] score: 2 * [int] }
Run this command:
cue export --out openapi --no-defaults test.cue
The resulting OpenAPI schema will define the teams and score arrays with their type and length constraints, and no default fields—fully compliant with OpenAPI specs.
内容的提问来源于stack exchange,提问作者rob74

