Golang中的面向对象 Yang

package main

import (
	"fmt"
	"math"
)

func main() {
	//method:method的概念,method是附属在一个给定的类型上的,
	//他的语法和函数的声明语法几乎一样,只是在func后面增加了一个receiver(也就是method所依从的主体)。
	//method的语法如下:
	//func(r ReceiverType) funcName(parameters)(results)
	//虽然method的名字一模一样,但是如果接收者不一样,那么method就不一样
	//method里面可以访问接收者的字段
	//调用method通过.访问,就像struct里面访问字段一样
	/*
		rectangle := Rectangle{5.1, 6.5}
		fmt.Printf("The Rectangle's area is %f\n", rectangle.area())

		circle := Circle{5.0}
		fmt.Printf("The Circle's area is %f\n", circle.area())
	*/

	//method 可以定义在任何你自定义的类型、内置类型、struct等各种类型上面
	//即以type定义的类型上面
	//type ages int
	//type money float32
	//type months map[string]int

	//指针作为receiver
	//如果一个method的receiver是*T,你可以在一个T类型的实例变量V上面调用这个method,而不需要&V去调用这个method
	//如果一个method的receiver是T,你可以在一个*T类型的变量P上面调用这个method,而不需要 *P去调用这个method
	/*
		box := Box{10, 20, 10, "white"}
		fmt.Printf("The Box's color is %s\n", box.color)
		//setColor接收的参数是指针类型,这里不需要使用*box来调用setColor()方法,go中会自动判断
		box.setColor("Red")
		fmt.Printf("The Box's color is %s\n", box.color)
	*/

	//method的继承
	//如果匿名字段实现了一个method,那么包含这个匿名字段的struct也能调用该method
	stu := student{Human{"yang", 26, "13883987410"}, "028110"}
	stu.sayHi()

	//method的继承 重写
	emp := employee{Human{"alex", 27, "15920580257"}, "010"}
	emp.sayHi()

}

type Rectangle struct {
	width  float32
	length float32
}

func (r Rectangle) area() float32 {
	return r.width * r.length
}

type Circle struct {
	r float64
}

func (c Circle) area() float64 {
	return c.r * c.r * math.Pi
}

type Color string
type Box struct {
	width, length, depth float32
	color                Color
}

//要改变box的颜色,需要用指针,而不是Box,传递这个Box的copy
func (T *Box) setColor(c Color) {
	//下面两种方法都可以为Box修改颜色

	T.color = c
	//go中不需要使用下面的方法来修改值,建议直接使用上面的方法调用
	//*T.color = c
}

type Human struct {
	name  string
	age   int
	phone string
}

type student struct {
	Human
	schoolNum string
}

type employee struct {
	Human
	employeeNo string
}

func (h *Human) sayHi() {
	fmt.Printf("Hi,I'm %s,I'm %d years old and my phone number is %s\n", h.name, h.age, h.phone)
}

//employee重写Human的sayHi()
func (e employee) sayHi() {
	fmt.Printf("Hi,I'm %s,I'm %d years old , my phone number is %s and my employee number is %s", e.Human.name, e.Human.age, e.Human.phone, e.employeeNo)
}
原文地址:https://www.cnblogs.com/Yang2012/p/3000290.html