mirror of
https://github.com/vlang/v.git
synced 2023-08-10 21:13:21 +03:00
cgen: fix initialising a map, using option type as value (#18540)
This commit is contained in:
parent
752e4c2e47
commit
34ac3269bc
@ -1888,7 +1888,11 @@ fn (mut g Gen) expr_with_tmp_var(expr ast.Expr, expr_typ ast.Type, ret_typ ast.T
|
||||
g.writeln('${g.typ(ret_typ)} ${tmp_var};')
|
||||
if ret_typ.has_flag(.option) {
|
||||
if expr_typ.has_flag(.option) && expr in [ast.StructInit, ast.ArrayInit, ast.MapInit] {
|
||||
g.write('_option_none(&(${styp}[]) { ')
|
||||
if expr is ast.StructInit && (expr as ast.StructInit).init_fields.len > 0 {
|
||||
g.write('_option_ok(&(${styp}[]) { ')
|
||||
} else {
|
||||
g.write('_option_none(&(${styp}[]) { ')
|
||||
}
|
||||
} else {
|
||||
is_ptr_to_ptr_assign = (expr is ast.SelectorExpr
|
||||
|| (expr is ast.Ident && !(expr as ast.Ident).is_auto_heap()))
|
||||
@ -3989,6 +3993,8 @@ fn (mut g Gen) map_init(node ast.MapInit) {
|
||||
}
|
||||
if value_sym.kind == .sum_type {
|
||||
g.expr_with_cast(expr, node.val_types[i], unwrap_val_typ)
|
||||
} else if node.val_types[i].has_flag(.option) {
|
||||
g.expr_with_opt(expr, node.val_types[i], unwrap_val_typ)
|
||||
} else {
|
||||
g.expr(expr)
|
||||
}
|
||||
|
@ -404,7 +404,7 @@ fn (mut g Gen) index_of_map(node ast.IndexExpr, sym ast.TypeSymbol) {
|
||||
if g.inside_return {
|
||||
g.typ(val_type)
|
||||
} else {
|
||||
g.typ(val_type.clear_flags(.option, .result))
|
||||
g.typ(val_type.clear_flags(.result))
|
||||
}
|
||||
}
|
||||
get_and_set_types := val_sym.kind in [.struct_, .map, .array]
|
||||
|
25
vlib/v/tests/option_map_init_test.v
Normal file
25
vlib/v/tests/option_map_init_test.v
Normal file
@ -0,0 +1,25 @@
|
||||
struct MyStruct {
|
||||
field int
|
||||
}
|
||||
|
||||
fn empty() map[string]?MyStruct {
|
||||
return {
|
||||
'key1': ?MyStruct(none)
|
||||
'key2': ?MyStruct{
|
||||
field: 10
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn test_main() {
|
||||
a := dump(empty())
|
||||
|
||||
b := dump(a['key2'])
|
||||
|
||||
assert b? == MyStruct{
|
||||
field: 10
|
||||
}
|
||||
|
||||
assert a['key1'] == none
|
||||
assert a['key2'] != none
|
||||
}
|
Loading…
Reference in New Issue
Block a user