Skip to content

Commit 6a112ea

Browse files
committed
Use go slice for nullable arrays
1 parent 1b9ecbc commit 6a112ea

File tree

2 files changed

+28
-4
lines changed

2 files changed

+28
-4
lines changed

packages/go-gen/src/main.rs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -473,6 +473,21 @@ mod tests {
473473
C Array[Array[Array[*string]]] `json:"c"`
474474
}"#,
475475
);
476+
477+
#[cw_serde]
478+
struct D {
479+
d: Option<Vec<String>>,
480+
nested: Vec<Option<Vec<String>>>,
481+
}
482+
let code = generate_go(cosmwasm_schema::schema_for!(D)).unwrap();
483+
assert_code_eq(
484+
code,
485+
r#"
486+
type D struct {
487+
D *[]string `json:"d,omitempty"`
488+
Nested Array[*[]string] `json:"nested"`
489+
}"#,
490+
);
476491
}
477492

478493
#[test]

packages/go-gen/src/schema.rs

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -209,11 +209,20 @@ pub fn type_from_instance_type(
209209
// for nullable array item types, we have to use a pointer type, even for basic types,
210210
// so we can pass null as elements
211211
// otherwise they would just be omitted from the array
212-
replace_custom_type(&if item_type.nullability == Nullability::Nullable {
213-
format!("Array[*{}]", item_type.name)
212+
let maybe_ptr = if item_type.nullability == Nullability::Nullable {
213+
"*"
214214
} else {
215-
format!("Array[{}]", item_type.name)
216-
})
215+
""
216+
};
217+
let ty = if t.contains(&InstanceType::Null) {
218+
// if the array itself is nullable, we can use a native Go slice
219+
format!("[]{maybe_ptr}{}", item_type.name)
220+
} else {
221+
// if it is not nullable, we enforce empty slices instead of nil using our own type
222+
format!("Array[{maybe_ptr}{}]", item_type.name)
223+
};
224+
225+
replace_custom_type(&ty)
217226
} else {
218227
unreachable!("instance type should be one of the above")
219228
})

0 commit comments

Comments
 (0)