Shift on sum types #18370
-
Doing some testing, trying to work with x.json2 import x.json2 as json
fn new_flash(mut data map[string]json.Any, value json.Any) {
flashes_key := 'flashes'
if existing_data := data[flashes_key] {
existing_data << value // add one json.Any to existing []json.Any
data[flashes_key] = existing_data
} else {
mut new_array := []json.Any{}
new_array << value
data[flashes_key] = new_array
}
}
fn get_flashes(mut data map[string]json.Any) ?json.Any {
flashes_key := 'flashes'
if existing_data := data[flashes_key] {
data.delete(flashes_key)
return existing_data
}
return none
}
fn main() {
mut flashes := map[string]json.Any{}
mut flash_zero := []json.Any{}
flash_zero << 'test_zero'
flash_zero << 0000
flash_zero << json.null
new_flash(mut flashes, flash_zero)
mut flash_one := []json.Any{}
flash_one << 'test_one'
flash_one << 111111
flash_one << json.null
new_flash(mut flashes, flash_one)
get_flashes(mut flashes)
}
|
Beta Was this translation helpful? Give feedback.
Answered by
einar-hjortdal
Jun 7, 2023
Replies: 1 comment
-
Solved by using type refinement fn new_flash(mut values map[string]json.Any, value json.Any) {
flashes_key := 'flashes'
if existing_data := values[flashes_key] {
if existing_data is []json.Any {
values[flashes_key] = arrays.concat(existing_data, value)
} else {
mut data := []json.Any{}
data << existing_data
values[flashes_key] = arrays.concat(data, value)
}
} else {
values[flashes_key] = value
}
} |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
einar-hjortdal
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Solved by using type refinement