Char::Reader is defined in the standard library as a Struct
. What was the reasoning behind choosing a Struct
instead of a Class
?
I think that was choosen for performance reasons. According to the docs:
A struct is mostly used for performance reasons to avoid lots of small memory allocations when passing small copies might be more efficient.
So how do you choose between a struct and a class? The rule of thumb is that if no instance variable is ever reassigned, i.e. your type is immutable, you could use a struct, otherwise use a class.
Char::Reader
is mutable (because has instance variables reassigned), but it seems to be safe enough to do what the compiler internals do even if reader
is a struct:
reader = Char::Reader.new(pattern)
while reader.has_next?
char = reader.current_char
reader = check_char reader, char
reader.next_char
end