tags:

views:

141

answers:

2

This function in pkg go/token makes me wonder why we need a method that returns the receiver itself.

// Token source positions are represented by a Position value.
// A Position is valid if the line number is > 0.
//
type Position struct {
    Filename string; // filename, if any
    Offset   int;    // byte offset, starting at 0
    Line     int;    // line number, starting at 1
    Column   int;    // column number, starting at 1 (character count)
}


// Pos is an accessor method for anonymous Position fields.
// It returns its receiver.
//
func (pos *Position) Pos() Position { return *pos }
+5  A: 

This is for the case where you are using anonymous fields to "subclass" the Position:

A field declared with a type but no explicit field name is an anonymous field. Such a field type must be specified as a type name T or as a pointer to a type name *T, and T itself may not be a pointer type. The unqualified type name acts as the field name.

So if you subclass Position in this way, it may be desirable for callers to be able to access the "parent" Position structure (ex: if you want to call String() on the position itself, as opposed to the subtype). Pos() returns it.

Suppressingfire
+5  A: 

In a struct like this (from pkg/go/ast/ast.go), the token.Position below is a struct field but it doesn't have any name:

// Comments

// A Comment node represents a single //-style or /*-style comment.
type Comment struct {
    token.Position;         // beginning position of the comment
    Text            []byte; // comment text (excluding '\n' for //-style comments)
}

Thus, how do you access it, when it doesn't have a name? That is what .Pos() does. Given a Comment node, you can get its token.Position by using the .Pos method on it:

 comment_position := comment_node.Pos ();

Here comment_position now contains the contents of the un-named ("anonymous") struct field token.Position.

Kinopiko