Private struct members

I think a really simple and already available solution for a “read only” public API would be to introduce a “pattern” by using immutable references.

Example:

struct Incrementer:
    """A simple struct to demonstrate the use of a read-only public API in Mojo.
    
    It has a method to increment a count and a read-only method to access the count.
    """

    var _count: Int

    fn increment(mut self):
        self._count += 1

    @always_inline
    fn count(read self) -> ref [ImmutableAnyOrigin] Int:
        return self._count

    fn __init__(out self):
        self._count = 0


fn main() raises:
    var inc = Incrementer()

    # Immutable reference to the count
    ref count = inc.count()

    # This will raise an error because count_ref is immutable
    # count += 100  # error: count_ref is immutable

    # Print the current count
    print("Initial count:", count)

    # Increment the count using the method
    inc.increment()

    # Print the updated count
    print("Updated count:", count)

So the pattern is:

  • var _foo: T
    for non public access and
  • fn foo(read self) -> ref [ImmutableAnyOrigin] T: return self._foo
    for public read only access.

I think @always_inline will even remove the function indirection.