07月19日, 2018

goweb-034-golang-方法

面向对象编程(OOP)的三大特征分别为封装、继承和多态。 封装,是指利用抽象数据类型对数据信息以及对数据。。。。。。。此处省略3万字
alt

方法声明

  • 在函数声明时,在其名字之前放上一个变量,即是一个方法。
  • 这个附加的参数会将该函数附加到这种类型上,即相当于为这种类型定义了一个独占的方法。

    package main
    
    import (
    	"fmt"
    )
    
    //Point 一个点
    type Point struct {
    	X, Y float64
    }
    
    //Format 格式化输出
    func (p Point) Format() {
    	fmt.Println("x:", p.X, "y:", p.Y)
    }
    func main() {
    	var p Point
    	p.Format()
    }
    

附加的参数p,叫做方法的接收器(receiver),可以任意的选择接收器的名字。 > 本质类似于其他OOP绑定方法到this需要额外的成本。

//Point 一个点
type Point struct {
	X, Y float64
}
//Format 格式化输出
func Format(p Point) {
	fmt.Println("x:", p.X, "y:", p.Y)
}
func main() {
	var p Point
	Format(p)
}

指针接收者

当需要改变接收者时或者接收者变量本身比较大时可使用指针作为接收者。

func (p *Point) Scale(rate float64) {
	p.X *= rate
	p.Y *= rate
}

无论methodreceiver是指针类型还是非指针类型,都是可以通过指针/非指针类型进行调用的,编译器会帮你做类型转换。

//Point 一个点
type Point struct {
	X, Y float64
}

//Format 格式化输出
func (p Point) Format() {
	fmt.Println("x:", p.X, "y:", p.Y)
}

//Scale 缩放
func (p *Point) Scale(rate float64) {
	p.X *= rate
	p.Y = p.Y * rate
}
func main() {
	var p = Point{1, 2}
	var ptr = &Point{3, 4}
	p.Scale(2)
	p.Format()

	ptr.Scale(2)
	ptr.Format()
}

alt

综合示例

package main

import (
	"fmt"
)

//Point 一个点
type Point struct {
	X, Y float64
}

//Format 格式化输出
func (p Point) Format() {
	fmt.Println("x:", p.X, "y:", p.Y)
}

//Print 打印
func (p *Point) Print() {
	fmt.Println("x:", p.X, "y:", p.Y)
}

//Circle 一个圆
type Circle struct {
	Point  
	Radius float64 //半径
}

//Print 打印
func (c *Circle) Print() {
	fmt.Println("x:", c.X, "y:", c.Y, "r:", c.Radius)
}

func main() {
	var c = Circle{
		Point{1, 2},
		10,
	}
	// 调用 Point的方法
	c.Format() //x: 1 y: 2
	// Circle的Print 方法
	// 覆盖
	// Point的Print方法
	c.Print()
	// 调用Point的Print方法
	c.Point.Print()
	Circle{}.Format() //x: 0 y: 0
        //不能在一个不能寻址的对象上调用指针接收者的方法
	//Circle{}.Print()//cannot call pointer method on Circle literal
}

本文链接:/posts/goweb-034/

-- EOF --