Golang中函数定义语法:Func (r receiver) identifier(parameters) (return(s)){...}详解
Golang中函数定义语法:Func (r receiver) identifier(parameters) (return(s)){…}详解
package main
import "fmt"
type person struct {
first string
last string
}
type secretAgent struct {
person
ltk bool
}
//func (r receiver) identifier(parameters) (return(s)){...}
func (s secretAgent) speak() {
fmt.Println("I am", s.first, s.last)
}
func main() {
sa1 := secretAgent{
person: person{
first: "James",
last: "Bond",
},
ltk: true,
}
fmt.Println(sa1)
sa1.speak()
}
我知道接收器(receiver)的作用是让只有该类型的值才能访问这个函数……在这个例子中,只有 secretAgent 类型的值才能访问。但是,它旁边的 s 是什么意思?它相当于 func speak() 内部的一个参数吗……
更多关于Golang中函数定义语法:Func (r receiver) identifier(parameters) (return(s)){...}详解的实战教程也可以访问 https://www.itying.com/category-94-b0.html
太棒的比喻。我来自JavaScript背景,所以这真的让我豁然开朗。
更多关于Golang中函数定义语法:Func (r receiver) identifier(parameters) (return(s)){...}详解的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
接收器使用两个标识符来指定,第一个指定了在方法体内使用的名称,第二个指定了其类型。
这与常规函数参数非常相似,不同之处在于只能有一个接收器。
s 类似于经典面向对象编程语言中的 this。当你的方法被调用时,s 包含了调用该方法的“对象”,在你的例子中,它将包含在 main 函数中被称为 sa1 的那个东西。这就像你定义了:
func speak(s secretAgent) { ...}
并像这样调用它:
speak(sa1)
在Go语言中,接收器声明中的 s 是接收器变量名,它确实类似于函数参数,允许在方法内部访问接收器类型的实例。
package main
import "fmt"
type Counter struct {
value int
}
// s 是接收器变量,可以在方法内部访问
func (s Counter) Increment() Counter {
s.value++
return s
}
// 使用指针接收器,可以修改原实例
func (s *Counter) IncrementByRef() {
s.value++
}
func main() {
c1 := Counter{value: 5}
// 值接收器 - 操作副本
result := c1.Increment()
fmt.Printf("值接收器: c1.value = %d, result.value = %d\n",
c1.value, result.value) // c1.value = 5, result.value = 6
// 指针接收器 - 操作原实例
c2 := &Counter{value: 5}
c2.IncrementByRef()
fmt.Printf("指针接收器: c2.value = %d\n", c2.value) // c2.value = 6
}
接收器变量 s 的作用域限定在方法体内,其命名遵循Go的变量命名规则。当使用值接收器时,s 是原实例的副本;使用指针接收器时,s 指向原实例。
type Rectangle struct {
width, height float64
}
// 值接收器方法
func (r Rectangle) Area() float64 {
return r.width * r.height
}
// 指针接收器方法
func (r *Rectangle) Scale(factor float64) {
r.width *= factor
r.height *= factor
}
func main() {
rect := Rectangle{width: 10, height: 5}
area := rect.Area() // 通过值访问
fmt.Printf("面积: %.2f\n", area) // 面积: 50.00
rect.Scale(2) // 通过指针修改
fmt.Printf("缩放后: %.2f x %.2f\n", rect.width, rect.height) // 缩放后: 20.00 x 10.00
}
接收器变量名 s 可以任意命名,但通常使用类型名称的首字母或简写。在您的示例中,s 代表 secretAgent 类型的实例,可以在 speak() 方法内部访问该实例的字段和方法。

