Go之method方法

1. 方法的声明

package main
import (
	"fmt"
	"math"
)

type Rectrangle struct {
	width, height float64
}
type Circle struct {
	radius float64
}
// 方法:在func关键字和方法名之间加上(接收器)
// 方法中method名可以相同,接收器不一样,则方法就不一样
// method里面可以访问接收者的字段
// 调用method通过.访问,就像struct里面访问字段一样
func (r Rectrangle) area() float64 {
	return r.height * r.width
}
// Go不是一种纯粹面向对象的编程语言,它不支持类。因此,类型的方法是一种实现类似于类的行为的方法。
// 相同名称的方法可以在不同的类型上定义,而具有相同名称的函数是不允许的。假设我们有一个正方形和圆形的结构。可以在正方形和圆形上定义一个名为Area的方法。这是在下面的程序中完成的
func (c Circle) area() float32 {
	return float32(c.radius * c.radius * math.Pi)
}
func main() {
	fmt.Println("Area of rect is:", Rectrangle{12, 1}.area())
	fmt.Println("Area of circle is:", Circle{5}.area())
}

运行结果:

Area of rect is: 12
Area of circle is: 78.53982

2. 方法的继承和重写

package main
import (
	"fmt"
	"math"
)

// 方法和函数的区别:
// Go不是一种纯粹面向对象的编程语言,它不支持类。因此,类型的方法是一种实现类似于类的行为的方法。
// 相同名称的方法可以在不同的类型上定义,而具有相同名称的函数是不允许的。假设我们有一个正方形和圆形的结构。可以在正方形和圆形上定义一个名为Area的方法。
type Rectrangle struct {
	width, height float64
}
type Circle struct {
	radius float64
	Rectrangle
}

// 方法:在func关键字和方法名之间加上(接收器)
// Rectrangle定义了method
func (r Rectrangle) area() float64 {
	// method里面可以访问接收者的字段,调用method通过.访问,就像struct里面访问字段一样
	return r.height * r.width
}
// 方法中method名可以相同,接收器不一样,则方法就不一样
// Circle的method重写Rectrangle的method
func (c Circle) area() float32 {
	return float32(c.radius * c.radius * math.Pi)
}

// 指针作为接收者,会真正改变接收者的数据,否则只是获取了一个copy
func (r *Rectrangle) setval() {
	r.height = 5
}
func main() {
	// 通过.操作符调用方法
	fmt.Println("Area of rect is:", Rectrangle{12, 1}.area())
	fmt.Println("Area of circle is:", Circle{ 5, Rectrangle{0,0}}.area())
	// 指针作为接收器,会对数据进行改写
	p := Rectrangle{1, 2}
	s := p
	p.setval()
	fmt.Println("height of p is",p.height,"\nheight of s is", s.height)
	// 方法的继承:如果匿名字段实现了一个method,那么包含这个匿名字段的struct也能调用该method
	mark := Circle{10, Rectrangle{8, 9}}
	mark.setval()
	fmt.Println("Area of mark is:", mark.height)
}

运行结果:

Area of rect is: 12
Area of circle is: 78.53982
height of p is 5 
height of s is 2
Area of mark is: 5

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值