Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Methods 返回接收器本身(Go)的方法的目的是什么?_Methods_Oop_Go - Fatal编程技术网

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

Methods 返回接收器本身(Go)的方法的目的是什么?,methods,oop,go,Methods,Oop,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; //

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 }

这适用于您使用“子类化”职位的情况:

使用类型声明但没有显式字段名的字段是匿名字段。这种字段类型必须指定为类型名T或指向类型名*T的指针,而T本身可能不是指针类型。非限定类型名用作字段名

因此,如果您以这种方式对Position进行子类化,调用方可能希望能够访问“父”Position结构(例如:如果您希望调用Position本身的
String()
,而不是子类型)
Pos()
返回它。

在这样的结构中(从),下面的
标记。位置是一个结构字段,但没有任何名称:

// 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)
}
因此,当它没有名称时,如何访问它?这就是
.Pos()
所做的。给定注释节点,您可以使用其上的
.Pos
方法获取其
标记.Position

 comment_position := comment_node.Pos ();
此处
comment\u position
现在包含未命名(“匿名”)结构字段
token.position
的内容