Struct field accessor function

136 views
Skip to first unread message

Pierre Durand

unread,
Aug 7, 2026, 1:08:20 PM (9 days ago) Aug 7
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 ?

Wendell Rios

unread,
Aug 7, 2026, 4:25:36 PM (9 days ago) Aug 7
to golang-nuts
Hi Pierre, I believe that what you want already exists, albeit with a slight different syntax and type positioning: 

package main

import "fmt"


type MyType struct {
Foo int
}

func (m *MyType) f() *int {
return &m.Foo
}

func main() {
v := &MyType{Foo: 123}
i := v.f
fmt.Println(*i()) // Prints: 123
*(i()) = 456
fmt.Println(v.Foo) // Prints: 456

Pierre Durand

unread,
Aug 7, 2026, 4:44:11 PM (9 days ago) Aug 7
to golang-nuts
Not exactly.

Actually this syntax is already possible for methods:

func main() {
f := (*bytes.Buffer).String
b := bytes.NewBufferString("test")
fmt.Println(f(b))
}

I would like to extend it to struct fields.

And I want to be able to do it on types I didn't create/don't own.
That's why I don't want to declare a new method on the type (otherwise I could simply add a getter/setter).

Axel Wagner

unread,
Aug 8, 2026, 1:38:58 AM (9 days ago) Aug 8
to Pierre Durand, golang-nuts
Personally, I mostly like this. MyType.Foo currently has no meaning if Foo is a field and it is not a bad syntax for this concept. If I objected to it, it would be because I'm not sure how frequently it is needed (the main usecase I would have is sorting by a field).

I think it makes sense to file this as a language change proposal (though it is probably a relatively low priority change, so I'm not sure we'd do it any time soon).

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion visit https://groups.google.com/d/msgid/golang-nuts/6150ff18-2956-4b2e-be40-7cf95a4207ffn%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages