go1.26.0: new(value), recursive generic constraints
Changes to the language
he built-in new function, which creates a new variable, now allows its operand to be an expression, specifying the initial value of the variable.
This feature is particularly useful when working with serialization packages such as encoding/json or protocol buffers that use a pointer to represent an optional value, as it enables an optional field to be populated in a simple expression, for example:
import "encoding/json"
type Person struct {
Name string `json:"name"`
Age *int `json:"age"` // age if known; nil otherwise
}
func personJSON(name string, born time.Time) ([]byte, error) {
return json.Marshal(Person{
Name: name,
Age: new(yearsSince(born)),
})
}
func yearsSince(t time.Time) int {
return int(time.Since(t).Hours() / (365.25 * 24)) // approximately
}The restriction that a generic type may not refer to itself in its type parameter list has been lifted. It is now possible to specify type constraints that refer to the generic type being constrained. For instance, a generic type Adder may require that it be instantiated with a type that is like itself:
type Adder[A Adder[A]] interface {
Add(A) A
}
func algo[A Adder[A]](x, y A) A {
return x.Add(y)
}Previously, the self-reference to Adder on the first line was not allowed. Besides making type constraints more powerful, this change also simplifies the spec rules for type parameters ever so slightly.
Did you enjoy this article?
Recommend it — Standard Reader surfaces well-loved writing to more readers across the network.