返回接收器本身(Go)的方法的目的是什么?

Ran*_*ku' 2 oop methods go

pkg go/token中的这个函数让我想知道为什么我们需要一个返回接收器本身的方法.

// 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 }
Run Code Online (Sandbox Code Playgroud)

Sup*_*ire 5

这适用于您使用匿名字段 "子类化"位置的情况:

使用类型但没有显式字段名称声明的字段是匿名字段.必须将此类字段类型指定为类型名称T或指定类型名称*T的指针,并且T本身可能不是指针类型.非限定类型名称充当字段名称.

因此,如果以这种方式对Position进行子类化,则可能需要调用者能够访问"父"位置结构(例如:如果要调用String()位置本身,而不是子类型).Pos()归还它.


小智 5

在这样的结构中(来自pkg/go/ast/ast.go),token.Position下面是一个struct字段,但它没有任何名称:

// 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)
}
Run Code Online (Sandbox Code Playgroud)

因此,当它没有名称时,你如何访问它?这是做什么的.Pos().给定一个Comment节点,你可以token.Position通过使用.Pos它的方法得到它:

 comment_position := comment_node.Pos ();
Run Code Online (Sandbox Code Playgroud)

这里comment_position现在包含未命名("匿名")结构字段的内容token.Position.