Interfaces & getters/setters

1,795 views
Skip to first unread message

Mark Summerfield

unread,
May 13, 2011, 4:14:21 AM5/13/11
to golang-nuts
Hi,

Currently interfaces may only contain method signatures. So, if I want
an interface to specify that an object has a method, M() _and_ a field
F, I must do this (untested):

type I interface {
M()
F() int
SetF(int)
}

type T struct {
f int
g string
}
func (t T) M() { fmt.Println(t.f, t.g) }
funt (t T) F() int { return t.f }
funt (t* T) SetF(f int) { t.f = f }

This forces me to create a getter and setter for every single type that
implements I.

But if interfaces could also specify fields then the above would
simplify to:

type I interface {
M()
F int
}

type T struct {
F int
g string
}
func (t T) M() { fmt.Println(t.f, t.g) }

This doesn't require any getters or setters for types that implement I.

I realize that this wouldn't appeal to OO purists, but I think it would
be useful and reduce code size (well, it would for one of my projects).

But maybe this has been thought of before and found wanting?

--
Mark Summerfield, Qtrac Ltd, www.qtrac.eu
C++, Python, Qt, PyQt - training and consultancy
"Programming in Go" - ISBN 0321774639
http://www.qtrac.eu/gobook.html

Paulo Pinto

unread,
May 13, 2011, 4:21:24 AM5/13/11
to golang-nuts
I guess that this could be better done if Go supported properties.

Jan Mercl

unread,
May 13, 2011, 4:59:34 AM5/13/11
to golan...@googlegroups.com
On Friday, May 13, 2011 10:14:21 AM UTC+2, Mark wrote:

But maybe this has been thought of before and found wanting?


Yeah, please search the list. This proposal was (sometimes heatedly) discussed IIRC more than once before.
The IMO most important argument against was not in any subjective OOP pureness but about losing the behavior/data orthogonality with this approach.

jimt

unread,
May 13, 2011, 10:33:20 AM5/13/11
to golan...@googlegroups.com
The Go way of doing this is to use type embedding: http://pastie.org/1896971
Reply all
Reply to author
Forward
0 new messages