Struct field accessor function

9 views
Skip to first unread message

Pierre Durand

unread,
1:08 PM (3 hours ago) 1:08 PM
to golang-nuts
Hello

I just had an idea about struct field accessor function.

type MyType struct {
Foo int
}

Currently if we use `MyType.Foo`, it's a compile error: "type MyType has no method Foo".

My idea is to add syntactic sugar on this expression.
It would be a function with 1 parameter (type of the struct), and 1 returned value (type is pointer to the field type).
So we don't need to define a closure.

It would allow to write this kind of code:

func main() {
type MyType struct {
Foo int
}
f := MyType.Foo // Type is: func(MyType) *int
v := MyType{Foo: 123}
i := *f(v)
fmt.Println(i) // Prints: 123
*f(v) = 456
fmt.Println(v.Foo) // Prints: 456
}

We should also allow to define it on a pointer: f := (*MyStruct).Foo

I don't remember similar proposal (or maybe I didn't search properly).
WDYT ?
Would it be helpful ?
Should I write a formal proposal ?
Reply all
Reply to author
Forward
0 new messages