V: Better type check in if, match...

Created on 7 Dec 2020  路  3Comments  路  Source: vlang/v


V version: V 0.1.30 5e59718.bac6be2
OS: linux, Linux version 5.4.72-gentoo (root@plasma) (gcc version 9.3.0 (Gentoo 9.3.0-r1 p3))

What did you do?

enum Color {
    red
    green
    blue
}
fn main() {
    color_1 := .red
    color_2 := if true {.red} else {.blue}
}

What did you expect to see?
Correct asignation of the var color_2, similar to color_1

What did you see instead?

check.v:8:5: error: expected type is not an enum (`none`)
    6 | fn main() {
    7 |     color_1 := .red
    8 |     color_2 := if true {.red} else {.blue}
      |     ~~~~~~~
    9 | }
Bug

Most helpful comment

That's exactly right. The compiler doesn't know know which enum has to be used.

Once it knows the type, you can do e.g. if color == .red {

Perhaps this can be documented a bit clearer.

All 3 comments

Hi @ejtizado I don't think this should work. The reason being is that color_1 & color_2 are new variables being declared, in this example there is only one enum Color with the values .red & .blue so you could argue the compiler should make the assumption that Color is the enum the user wanted to use. But what if there are multiple enum's which happen to have the same value, then there is no way to infer which one the user wanted. For this reason I think its best to always require explicit Color.red for the deceleration, so the usage will always be the same, rather than working in some cases and not in others.

Of course, In cases where it can't be inferred then the compiler could just error. I'm not sure about this one.

@medvednikov, @spytheman what do you think?

That's exactly right. The compiler doesn't know know which enum has to be used.

Once it knows the type, you can do e.g. if color == .red {

Perhaps this can be documented a bit clearer.

The compiler could be check the return types of if and else and if both are the same the compiler could assume the Color type to the new variable. The same occur with math:

a = match n {
      'red' {.red}
      'green' {.green}
      'blue' {.blue}
}

I labeled the issue as bug but think more than bugs is a request!
Thanks!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

cjmxp picture cjmxp  路  3Comments

PavelVozenilek picture PavelVozenilek  路  3Comments

radare picture radare  路  3Comments

choleraehyq picture choleraehyq  路  3Comments

taojy123 picture taojy123  路  3Comments