This program gives a compile error:
fn f() int? {
return 5
}
fn main() {
mut o := f()
o = 4 // line 7
}
test.v:7
cannot use type `int` as type `Option_int` in assignment
(BTW, shouldn't optional types be written ?T instead of T?, so it reads optional T left to right like Go type modifier philosophy, not T optional? ?T is how Zig writes them).
Edit: Clarify last sentence.
This error is correct.
You need to unwrap an optional with or.
fn f() int? {
a := 5
return a
}
fn main() {
mut o := f() or {
return
}
o = 4
}
T? is the syntax used by Swift, C#, Kotlin. I think there are more.
mut o := f() or {
@medvednikov No, I want o to be an optional. Optionals should allow assignment from their value type.
T? is the syntax used by Swift, C#, Kotlin. I think there are more.
Yes, but those languages don't use Go syntax for types (read left to right), they read right to left.
Swift and Kotlin do.
Optionals should allow assignment from their value type.
Indeed. This is not implemented yet.
I tried to find pointer and array syntax in Swift and Kotlin, in what I saw they don't seem to use Go *T, []T type syntax, but it was hard to find clear documentation. But another argument is with optional pointers:
fn f() *int?
Does f return a pointer to an optional int, or an optional pointer to an int? With ?T syntax, it's clear:
?*int // optional pointer to int
*?int // pointer to optional int
I don't think pointer optionals are going to be allowed.
Pointers in general should be rarely used in V.
I don't think pointer optionals are going to be allowed.
How should we model pointers that can be null then? This is a key motivation for optional types, replacing null. How will we port programs from other languages to V?
Pointers in general should be rarely used in V.
Reference types are a crucial feature to refer to heap allocated data, or the same data from multiple places, what will we use instead of pointers?
Right now there's isnil builtin function to handle C nil pointers, but using optionals sounds like a better idea.
Then it makes sense to use ?*int syntax.
Great! When the source is available, I might be able to update the compiler to use ?T instead of T?. Let me know if you want me to update the docs and examples if you decide to implement the change.
This particular problem has just been fixed, although optionals still need lots of work.
?T syntax has been implemented to replace T?
opt_int = 5 is now allowed.
Returning an integer literal doesn't work at the moment,
this will compile:
fn f() ?int {
res := 5
return res
}
fn main() {
mut o := f()
o = 4
}
o still can't be used properly yet.
?T syntax has been implemented to replace T?
opt_int = 5 is now allowed.
Great, thanks. I filed the other issues you mentioned as part of #261.
Most helpful comment
Right now there's
isnilbuiltin function to handle C nil pointers, but using optionals sounds like a better idea.Then it makes sense to use
?*intsyntax.