With the introduction of ref
variable bindings (see variable bindings proposal) we gained two new powerful features concerning immutable references:
- The ability to implicitly declare (deeply) immutable values
- Binding variables to immutable references
I think it would be a useful enhancement to allow for explicit read
value bindings to improve code readability and ease adoption.
Take this example:
import time
fn as_read[T: AnyType](read x: T) -> ref [ImmutableAnyOrigin] T:
"""Helper function to return a value as a immutable reference."""
return x
fn print_elapsed_time(read value: Int):
print("elapsed time =", time.perf_counter_ns() - value, "ns")
fn main() raises:
# immutable value
ref start_time = as_read(time.perf_counter_ns())
# start_time *= 2 # error: start_time is immutable
# deeply immutable value
ref list = as_read[List[List[Int]]]([[0, 1], [2, 3]])
# immutable reference binding
ref list_val = list[0][0]
# list_val += 1 # error: list_val is immutable
print(list_val) # ok
# sub_list is an immutable reference binding
for sub_list in list:
# sub_list[0] += 1 # error: sub_list is immutable
print(sub_list[0]) # ok
print_elapsed_time(start_time) # ok
By introducing explicit read
value bindings, the code would be self explaining and the as_read()
helper function would not be needed anymore:
import time
fn print_elapsed_time(read value: Int):
print("elapsed time =", time.perf_counter_ns() - value, "ns")
fn main() raises:
read start_time = time.perf_counter_ns()
# start_time *= 2 # error: start_time is immutable
read list = [[0, 1], [2, 3]]
read list_val = list[0][0]
# list_val += 1 # error: list_val is immutable
print(list_val) # ok
for read sub_list in list:
# sub_list[0] += 1 # error: sub_list is immutable
print(sub_list[0]) # ok
print_elapsed_time(start_time) # ok
Somehow this is just “syntactic sugar” for already available functionality and can be introduced at any time without breaking changes. Nevertheless I think it would be a nice enhancement and fit well with the variable bindings proposal and the current state of the ownership model and argument conventions.