I'm opening this issue as a place to record this idea, which has come up several times. I'm not personally in favor of this proposal. An example of an earlier discussion: https://groups.google.com/d/msg/golang-nuts/ZJ5DEv_36S8/opZ__-l6XxAJ .
The proposal: allow interface types to list fields, with types, as well as methods. An interface type that lists a field may only be implemented by a struct type that has a field with the same name and type.
For example:
type I interface {
F int
}
type S struct {
E, F, G int
}
// S has no methods.
var V1 I = S{} // ok
var V2 I = &S{} // ok
func GetI(i I) int {
return i.F // ok
}
func SetI(i I, v int) {
i.F = v // ok
}
Note that since the interface type could be implemented by struct types that put the field at different offsets, the seemingly simple expressions/statements like i.F and i.F = v would most likely be implemented by function calls.
The advantage of this proposal is that when several different struct types have fields with the same names and types, and interface could be used to access those fields directly, rather than requiring each type to define boilerplate getter/setter methods.
A disadvantage is that it changes the meaning of an interface type from one that purely describes behavior to one that also describes implementation. This is particularly clear in the fact that an interface that defines a field can only be implemented by a struct type.
I'm opening this issue as a place to record this idea, which has come up several times. I'm not personally in favor of this proposal. An example of an earlier discussion: https://groups.google.com/d/msg/golang-nuts/ZJ5DEv_36S8/opZ__-l6XxAJ .
The proposal: allow interface types to list fields, with types, as well as methods. An interface type that lists a field may only be implemented by a struct type that has a field with the same name and type.
For example:
Note that since the interface type could be implemented by struct types that put the field at different offsets, the seemingly simple expressions/statements like
i.Fandi.F = vwould most likely be implemented by function calls.The advantage of this proposal is that when several different struct types have fields with the same names and types, and interface could be used to access those fields directly, rather than requiring each type to define boilerplate getter/setter methods.
A disadvantage is that it changes the meaning of an interface type from one that purely describes behavior to one that also describes implementation. This is particularly clear in the fact that an interface that defines a field can only be implemented by a struct type.