mirror of
https://github.com/vlang/v.git
synced 2023-08-10 21:13:21 +03:00
checker: allow none
to be casted to all option types, including aliases (#17348)
This commit is contained in:
parent
ce1978ecde
commit
8a1e90fff1
@ -2755,7 +2755,9 @@ fn (mut c Checker) cast_expr(mut node ast.CastExpr) ast.Type {
|
|||||||
if from_type == ast.void_type {
|
if from_type == ast.void_type {
|
||||||
c.error('expression does not return a value so it cannot be cast', node.expr.pos())
|
c.error('expression does not return a value so it cannot be cast', node.expr.pos())
|
||||||
}
|
}
|
||||||
if to_sym.kind == .sum_type {
|
if to_type.has_flag(.option) && from_type == ast.none_type {
|
||||||
|
// allow conversion from none to every option type
|
||||||
|
} else if to_sym.kind == .sum_type {
|
||||||
if from_type in [ast.int_literal_type, ast.float_literal_type] {
|
if from_type in [ast.int_literal_type, ast.float_literal_type] {
|
||||||
xx := if from_type == ast.int_literal_type { ast.int_type } else { ast.f64_type }
|
xx := if from_type == ast.int_literal_type { ast.int_type } else { ast.f64_type }
|
||||||
node.expr_type = c.promote_num(node.expr_type, xx)
|
node.expr_type = c.promote_num(node.expr_type, xx)
|
||||||
|
38
vlib/v/tests/cast_none_to_option_test.v
Normal file
38
vlib/v/tests/cast_none_to_option_test.v
Normal file
@ -0,0 +1,38 @@
|
|||||||
|
struct Test {}
|
||||||
|
|
||||||
|
type AliasType = Test
|
||||||
|
|
||||||
|
type I20 = int
|
||||||
|
|
||||||
|
type Byt = u8
|
||||||
|
|
||||||
|
fn test_cast_none() {
|
||||||
|
a := ?I20(none)
|
||||||
|
assert a == none
|
||||||
|
b := ?int(none)
|
||||||
|
assert b == none
|
||||||
|
c := ?i16(none)
|
||||||
|
assert c == none
|
||||||
|
d := ?u32(none)
|
||||||
|
assert d == none
|
||||||
|
e := ?u16(none)
|
||||||
|
assert e == none
|
||||||
|
f := ?u8(none)
|
||||||
|
assert f == none
|
||||||
|
g := ?Test(none)
|
||||||
|
assert g == none
|
||||||
|
h := ?AliasType(none)
|
||||||
|
assert h == none
|
||||||
|
i := ?Byt(none)
|
||||||
|
assert i == none
|
||||||
|
j := ?rune(none)
|
||||||
|
assert j == none
|
||||||
|
k := ?string(none)
|
||||||
|
assert k == none
|
||||||
|
l := ?[]Byt(none)
|
||||||
|
assert l == none
|
||||||
|
m := ?[]Test(none)
|
||||||
|
assert m == none
|
||||||
|
n := ?[]AliasType(none)
|
||||||
|
assert n == none
|
||||||
|
}
|
Loading…
x
Reference in New Issue
Block a user