diff --git a/vlib/v/checker/checker.v b/vlib/v/checker/checker.v index 3cf3d11db5..c037ddac88 100644 --- a/vlib/v/checker/checker.v +++ b/vlib/v/checker/checker.v @@ -2575,9 +2575,11 @@ pub fn (mut c Checker) expr(node ast.Expr) table.Type { // c.error('only $info.variants can be casted to `$typ`', node.pos) } } else { - // - c.error('cannot cast non sum type `$type_sym.source_name` using `as`', - node.pos) + mut s := 'cannot cast non-sum type `$expr_type_sym.source_name` using `as`' + if type_sym.kind == .sum_type { + s += ' - use e.g. `${type_sym.source_name}(some_expr)` instead.' + } + c.error(s, node.pos) } return node.typ.to_ptr() // return node.typ diff --git a/vlib/v/checker/tests/sum.out b/vlib/v/checker/tests/sum.out new file mode 100644 index 0000000000..330761e29c --- /dev/null +++ b/vlib/v/checker/tests/sum.out @@ -0,0 +1,27 @@ +vlib/v/checker/tests/sum.vv:5:8: error: cannot cast non-sum type `int` using `as` + 3 | fn non_sum() { + 4 | v := 4 + 5 | _ = v as rune + | ~~ + 6 | _ = v as Var + 7 | } +vlib/v/checker/tests/sum.vv:6:8: error: cannot cast non-sum type `int` using `as` - use e.g. `Var(some_expr)` instead. + 4 | v := 4 + 5 | _ = v as rune + 6 | _ = v as Var + | ~~ + 7 | } + 8 | +vlib/v/checker/tests/sum.vv:10:11: error: cannot cast `rune` to `Var` + 8 | + 9 | fn sum() { + 10 | _ := Var(`J`) + | ~~~ + 11 | mut s2 := Var('') + 12 | s2 = true +vlib/v/checker/tests/sum.vv:12:7: error: cannot assign `bool` to `s2` of type `Var` + 10 | _ := Var(`J`) + 11 | mut s2 := Var('') + 12 | s2 = true + | ~~~~ + 13 | } diff --git a/vlib/v/checker/tests/sum.vv b/vlib/v/checker/tests/sum.vv new file mode 100644 index 0000000000..1693732fa8 --- /dev/null +++ b/vlib/v/checker/tests/sum.vv @@ -0,0 +1,13 @@ +type Var = int | string + +fn non_sum() { + v := 4 + _ = v as rune + _ = v as Var +} + +fn sum() { + _ := Var(`J`) + mut s2 := Var('') + s2 = true +}