什么是 Crystal 的 Char::Reader 定义为结构而不是 Class?

What is Crystal's Char::Reader defined as a Struct and not a Class?

Char::Reader 在标准库中定义为 Struct。选择 Struct 而不是 Class 的原因是什么?

我认为选择它是出于性能原因。根据 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 是可变的(因为已重新分配了实例变量),但即使 reader 是一个结构,它似乎也足以安全地执行编译器内部的操作:

reader = Char::Reader.new(pattern)
while reader.has_next?
  char = reader.current_char
  reader = check_char reader, char
  reader.next_char
end