What do the brackets after func mean in Go?

huangapple go评论90阅读模式
英文:

What do the brackets after func mean in Go?

问题

作为一个Go语言初学者,我在代码中偶然发现了一段代码,在func后面直接跟着括号:

func (v Version) MarshalJSON() ([]byte, error) {
  return json.Marshal(v.String())
}

那么(v Version)是什么意思呢?

英文:

As a Go beginner, I stumbled across code where there are brackets directly after func

func (v Version) MarshalJSON() ([]byte, error) {
  return json.Marshal(v.String())
}

So what does (v Version) mean?
1: https://github.com/getlantern/lantern/blob/2.0.2/src/github.com/blang/semver/json.go#L8

答案1

得分: 14

这不是一个函数,而是一个方法。在这种情况下,它将MarshalJSON方法添加到Version结构体类型中。

v是接收到的值的名称(类似于Java方法中的this或Python中的self),Version指定了我们要添加方法的类型。

请参考go by example获取示例,以及规范获取更多详细信息。

英文:

This is not a function but a method. In this case, it adds the MarshalJSON method to the Version struct type.

The v is the name for the received value (and would be analogous to this in a Java method or self in Python), the Version specifies the type we're adding the method to.

See go by example for, well, an example, and the specification for more details.

huangapple
  • 本文由 发表于 2015年9月3日 03:42:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/32361778.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定