v icon indicating copy to clipboard operation
v copied to clipboard

Returning a value as an optional

Open ntrel opened this issue 7 years ago • 6 comments

[Edit: as mentioned here] Returning an int or *int as an optional function result does not compile in the playground:

fn f() ?int {
  return 4
}

fn g() ?*int {
  i:=5
  return &i
}

Returning a struct instance does work.

ntrel avatar Jun 17 '19 16:06 ntrel

Then:

fn main() {
	mut o := f()? // unexpected token: `?`
	mut o := f() // OK
	o = 4
	i := o or {return} // returns!
	println(i)
}}

The first f() call doesn't compile. Then with o = 4 main returns early. Commenting out o = 4 does work.

ntrel avatar Jun 17 '19 16:06 ntrel

This looks to be resolved and clarified. Refer to #67 for the explanation.

Bowero avatar Jun 26 '19 19:06 Bowero

@Bowero this issue continues on from that issue, read the discussion. Please reopen.

ntrel avatar Jun 26 '19 19:06 ntrel

I see. I was too quick with drawing a conclusion. My sincerest apologies.

Bowero avatar Jun 26 '19 21:06 Bowero

In the current version of v, this fails to compile, with the following message:

foo.v:6:3: error: expr(): bad token `:=`
    4 |
    5 | fn g() ?*int {
    6 |     i:=5
      |      ~~
    7 |     return &i
    8 | }

JalonSolov avatar Jun 19 '20 23:06 JalonSolov

It works now, just have to use &

fn g() ?&int {
  i:=5
  return &i
}

medvednikov avatar Jun 20 '20 00:06 medvednikov