1
0
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:
Felipe Pena 2023-02-19 13:56:14 -03:00 committed by GitHub
parent ce1978ecde
commit 8a1e90fff1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 41 additions and 1 deletions

View File

@ -2755,7 +2755,9 @@ fn (mut c Checker) cast_expr(mut node ast.CastExpr) ast.Type {
if from_type == ast.void_type {
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] {
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)

View 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
}