为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
犯罪嫌疑人X 2021-04-08 17:15:19
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 }
查看完整描述

2 回答

?
慕沐林林

TA贡献2016条经验 获得超9个赞

这是在您使用匿名字段将位置“子类化”的情况下:

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

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


查看完整回答
反对 回复 2021-04-26
?
千万里不及你

TA贡献1784条经验 获得超9个赞

在这样的结构中(来自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)

}

因此,当它没有名称时,如何访问它?那是什么.Pos()。给定一个Comment节点,您可以token.Position使用其.Pos上的方法来获取它:


 comment_position := comment_node.Pos ();

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


查看完整回答
反对 回复 2021-04-26
  • 2 回答
  • 0 关注
  • 216 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信