Open katat opened 3 weeks ago
Generic struct only can simplify repeated code, but also it is necessary when we want to use struct field to instantiate a generic method.
For example:
struct Uint8 { inner: Field, bit_len: Field, } fn Uint8.new(val: Field) -> Uint8 { let bit_len = 8; // range check let ignore_ = bits::to_bits(bit_len, val); return Uint8 { inner: val, bit_len: bit_len }; } fn Uint8.less_than(self, rhs: Uint8) -> Bool { return comparator::less_than(self.bit_len, self.inner, rhs.inner); }
With support of generic struct, struct Uint8 can be generalized as Uint<bit_len> generic over the size of bit len.
Uint8
Uint<bit_len>
Also the self.bit_len can be treated as a immutable constant so it can be as a constant argument to instantiate a generic function.
self.bit_len
Btw constants as field might still be useful. For example, if we want to track the bit number of something and only perform mod reductions or range checks when the bits get too large
Generic struct only can simplify repeated code, but also it is necessary when we want to use struct field to instantiate a generic method.
For example:
With support of generic struct, struct
Uint8
can be generalized asUint<bit_len>
generic over the size of bit len.Also the
self.bit_len
can be treated as a immutable constant so it can be as a constant argument to instantiate a generic function.