Parametric `var`

Hello, could parametric var be a solution ?

fn Widget[border: Bool = False]():
  @parameter
  if border:
    var b = Border()
  ...
  @parameter
  if border:
    b^.draw() #?
fn MyFunc[border: Bool = False]():
  var[border] b = Border()
  ...
  @parameter
  if border:
    b^.draw()

Such a thing might be addable in principle, but would need to justify its complexity if we wanted to add it.

I don’t think we’re prioritizing such things in the immediate future, and in the meantime you can use var b = Optional[Border]().

1 Like

For larecs, I have implemented a comptime version of optional, which has a zero memory footprint if it is empty. Maybe I should make a proposal to add it to the stlib =).

This makes the following possible:

from larecs.comptime_optional import ComptimeOptional
from sys.info import sizeof

struct S[has_value: Bool = False]:
   var _value: ComptimeOptional[Int, has_value]

   fn __init__(out self, value: ComptimeOptional[Int, has_value] = None):
      self._value = value


def main():
   s0 = S()
   s1 = S(1)

   print("Size of s0 =", sizeof[__type_of(s0)]())
   print("Size of s1 =", sizeof[__type_of(s1)]())

   @parameter
   if s0.has_value:
      print(s0._value.value())


   @parameter
   if s1.has_value:
      print(s1._value.value())

Output:

Size of s0 = 0
Size of s1 = 8
1
2 Likes