2009/11/25 roger peppe <
rogp...@gmail.com>:
> i suppose to take that to its logical conclusion,
> one should be also able to do:
>
> x := &int(7);
>
> and get a pointer to a heap allocated int containing the
> value 7.
>
> hmm. one part of me says "why not?" and the other
> isn't at all sure.
The problem is with the poor choice of the &T{...} syntax. The &
operator is not clear whether a new object is created or a pointer to
an existing object is returned. It returns a pointer to an existing
object if its argument denotes an object which obviously existed
before the expression started evaluation (e.g. a variable or a field
of an object), and it creates a new object if its argument obviously
describes contents of an object by listing its fields.
Since the two meanings use the same syntax, it is hard to extend it to
expressions which neither suggest an existing object nor a new object.
There are actually three conceptually separate cases:
- We always want a new object.
- We want the address of an existing object.
- We don't care when the object is created; this can only apply to
immutable values. The compiler can allocate the object statically if
its contents are always the same, and it can coalesce objects with the
same contents.
Since Go has poor support for immutable objects, the third case rarely
applies. We could have for example "new x" where x is any expression
of type T, returning T*, and "&x" which is valid only where x is an
lvalue.
--
Marcin Kowalczyk