Golang 如何向结构体类型添加方法
结构体由数据组成,除此之外,结构体还以方法的形式告知行为。附加到结构体的方法与常规函数的定义非常相似,唯一的区别是您需要另外指定其类型。
一个返回整数且不带参数的常规函数会长这样。
func function_name() int {
// 代码
}
将上述函数与类型 type_name() 关联会如下所示。
type type_name struct { }
func (m type_name) function_name() int {
// 代码
}
在下面的代码中,向一个名为 Rect 的结构体添加了一个 Area() 函数。这里,Area() 是明确与 Rect 类型一起使用的, func (re Rect) Area() int
示例:
package main
import "fmt"
// 定义一个结构体
type Rect struct {
len, wid int
}
func (re Rect) Area() int {
return re.len * re.wid
}
func main() {
r := Rect{10, 12}
fmt.Println("Length and Width are:", r)
fmt.Println("Area of Rectangle: ", r.Area())
}
输出结果:
Length and Width are: {10, 12}
Area of Rectangle: 120
Golang 不使用关键字 this 或 self ,而是在定义与类型关联的方法时,使用命名变量 (r Rect) (例如在上面的情况下),然后在该方法内使用变量 re 。
在上述代码中,实例 Rect 作为值传递给调用 Area() 方法。也可以通过引用进行传递。在调用该方法时,无论您用作调用实例的实例是指针还是值,Go 都会自动为您进行转换。
package main
import "fmt"
// 定义一个结构体
type Rect struct {
len, wid int
}
func (re Rect) Area_by_value() int {
return re.len * re.wid
}
func (re *Rect) Area_by_reference() int {
return re.len * re.wid
}
// 主函数
func main() {
r := Rect{10, 12}
fmt.Println("Length and Width is:", r)
fmt.Println("Area of Rectangle is:", r.Area_by_value())
fmt.Println("Area of Rectangle is:", r.Area_by_reference())
fmt.Println("Area of Rectangle is:", (&r).Area_by_value())
fmt.Println("Area of Rectangle is:", (&r).Area_by_reference())
}
输出结果:
Length and Width is: {10, 12}
Area of Rectangle is: 120
Area of Rectangle is: 120
Area of Rectangle is: 120
Area of Rectangle is: 120
在上面的代码中,我们定义了两个类似的方法,一个以指针形式接收实例(Rect),另一个以值的形式接收。两个方法都通过值 r 和地址 &r 调用。但由于 Golang 执行适当的转换,它显示相同的结果。