vlang / v

Simple, fast, safe, compiled language for developing maintainable software. Compiles itself in <1s with zero library dependencies. Supports automatic C => V translation. https://vlang.io
MIT License
35.5k stars 2.15k forks source link

comptime: support `$d()` in fixed size array `struct` fields #21731

Closed larpon closed 3 days ago

larpon commented 3 days ago

This PR adds support for:

struct St {
    fsa [$d('size', 4)]int
}

This makes it possible to define sizes on fixed arrays on structs in cases where you do not want to use a const. Using s in const s = $d('size', 4) for fixed array size may not always be desirable; since consts (especially if pub) can be used and imported anywhere by users that may not be aware that the const can be changed by the external world, this can be fatal or lead to hard-to-find errors - with this PR you can ensure that the size is only used where you intended it.

One thing I haven't addressed for now is:

struct St {
    fsa [$d('size', 4)]int = [1, 2, 3, 4] // TODO what to do if `size != 4`?
}

I can't really decide what to do in this case - one simple solution could be to ban default assignments if $d() is used as size quantifier. Ideas and comments are welcome :slightly_smiling_face:

spytheman commented 3 days ago

one simple solution could be to ban default assignments if $d() is used as size quantifier. Ideas and comments are welcome 🙂

I agree, that may be best for now, until someone has an actual use case for it, so that we can analyze a more concrete scenario.