tags:

views:

94

answers:

2

In day 2 of the go tutorial there is this exercise:

Why may it be useful to have a private type with exported fields?

For example:

package geometry

type point struct {
    X, Y int;
    name string;
}

Notice that point is lowercase and thus not exported, whereas the fields X and Y are uppercase and thus are. It seems to me, that in order to have access to one of the exported fields, you would have to be able to write something like.

p.X

But in order for that to be possible, p would have to have a declaration like such:

var p geomitry.point;

or

p := new(geomitry.point);

This however is not possible (afaik), since the type declaration for point isn't exported.

+4  A: 

But you could have a public constructor, right?

So if you had a NewGeometryPoint func defined, then you maybe could do (haven't tested against the compiler)

p := NewGeometryPoint(640,480);
fmt.Println("X:",p.X, "Y:",p.Y);
Suppressingfire
Yep, I tested this with the compiler, this does work.
Brian Campbell
Wow, I like that. It looks like I found my new technique.
sdellysse
+4  A: 

An abstract base type ?

package geometry

type point struct {
    X, Y int;
}

type Point struct {
    point;
    name string;
}

type Rect struct {
    P1, P2 point;
    name string;
}
ppierre