On Thu, Mar 15, 2012 at 6:43 PM, bearophile <[email protected]> wrote: > In my code I have seen that in some situations I'd like to do > something with structs that const doesn't allow me to do. There > are many different cases of such usage, the following isn't my > most common example, but it shows better what I mean: > > > import std.random: randomShuffle; > struct Foo { > const int x, y; > } > void main() { > auto foos = [Foo(1,2), Foo(3,4)]; > randomShuffle(foos); > } >
Maybe in this particular case what you really want to do is shuffle the indices. > > Here the Foo struct has two fields, they are tagged with const > because no method of Foo is ever allowed to change their value > once a Foo is built, and no one outside of Foo is allowed to > change them. So they are quite constant. > > On the other hand if I have two or more Foos I sometimes want to > rebind an old Foo with a new one (a simple variable assign), or > in this program I even want to shuffle them. Shuffling them > doesn't change the logically constant nature of their x and y > fields. > > So in a way here I am looking for a const that makes the struct > fields not mutable, but allows me to rebind the whole structs. > > Currently std.typecons.rebindable works only on class instances, > interfaces and arrays (std.typecons.rebindable seems to accept > fixed-sized arrays too, but I don't know if this meaningful & > good). So it's not a solution. > > I think the small problem shown here is not the logical const > needed for storing things like lazily computed hash values for > immutable structs. Here nothing inside Foo is allowed to change > once Foo is created (here I have not added mutable fields to Foo). > > In such situations I sometimes don't use const, or sometimes I > use class instances, or even pointers. > > Bye, > bearophile
