v icon indicating copy to clipboard operation
v copied to clipboard

Support optional fields

Open trufae opened this issue 3 years ago • 4 comments

V version: V 0.1.29 06f4d10 OS: macOS 10.15

What did you do?

struct Foo {
    magic int
}
struct Bar {
mut:
    foo ?Foo
}
fn test() {
    mut a := Bar{}
    a.foo = Foo{123}
    if f := a.foo {
        eprintln('$f.magic')
    }
}
fn main() {
    test()
}

v run

$ v run s.v
==================
                        ~ ^ ~~~~~~
/var/folders/12/517hk27n0pxbnbv9yxlh4jxm0000gn/T/v/s.4908626687390563266.tmp.c:8035:8: error: assigning to 'Option_main__Foo' (aka 'struct Option_main__Foo') from incompatible type 'main__Foo' (aka 'struct main__Foo')
        a.foo = (main__Foo){.magic = 123,};
              ^ ~~~~~~~~~~~~~~~~~~~~~~~~~~
13 warnings and 1 error generated.
...
==================
(Use `v -cg` to print the entire error message)

What did you expect to see?

working compilation

What did you see instead? struct fields cant be optional

trufae avatar Nov 02 '20 17:11 trufae

One option could be to make optional fields to be initialized to error('undefined')

trufae avatar Nov 03 '20 10:11 trufae

Hi @trufae ,

can you confirm that a problem still exists on a fresh V (0.2.4)?

ArtemkaKun avatar Feb 10 '22 17:02 ArtemkaKun

Still not fixed. this is the current output with latest V:

$ v run a.v
==================
   ^~~~~~~~~~~~~~~
/tmp/v_501/a.15754397149533176605.tmp.c:11146:8: error: assigning to 'Option_main__Foo' (aka 'struct Option_main__Foo') from incompatible type 'main__Foo' (aka 'struct main__Foo')
        a.foo = (main__Foo){.magic = 123,};
              ^ ~~~~~~~~~~~~~~~~~~~~~~~~~~
1 warning and 1 error generated.
...
==================
(Use `v -cg` to print the entire error message)

builder error:
==================
C error. This should never happen.

This is a compiler bug, please report it using `v bug file.v`.

https://github.com/vlang/v/issues/new/choose

You can also use #help on Discord: https://discord.gg/vlang

$

trufae avatar Feb 12 '22 11:02 trufae

bug.v:11:15: error: if guard condition expression is illegal, it should return optional
    9 |     mut a := Bar{}
   10 |     a.foo = Foo{123}
   11 |     if f := a.foo {
      |               ~~~
   12 |         eprintln('$f.magic')
   13 |     } else {}

ghost avatar Jul 23 '22 15:07 ghost