初识Go(6)

method

带有接收者的函数,我们称为 method

func (r ReceiverType) funcName(parameters) (results)



package main

import (

	"fmt"

	"math"

)

type Rectangle struct {

	width, height float64

}

type Circle struct {

	radius float64

}

func (r Rectangle) area() float64 {

	return r.width*r.height

}

func (c Circle) area() float64 {

	return c.radius * c.radius * math.Pi

}

func main() {

	r1 := Rectangle{12, 2}

	r2 := Rectangle{9, 4}

	c1 := Circle{10}

	c2 := Circle{25}

	fmt.Println("Area of r1 is: ", r1.area())//调用的都是area这个方法,但是接受的参数对象不一样

	fmt.Println("Area of r2 is: ", r2.area())

	fmt.Println("Area of c1 is: ", c1.area())

	fmt.Println("Area of c2 is: ", c2.area())

}

method名字一样,但是接受者的参数不一样,那就是两个method



func (b *Box) SetColor(c Color) {

	b.color = c

}

c就是普通函数接受的参数



指针作为Reciever

从上一个例子就可已看出,传入的Reciever是 *Box是个指针,为什么呢?

因为我们要修改color的值,如果传入的是Box,那么它是一个copy,并不能

作用于Box本身,所以传入的是一个指针。



如果一个 method 的 receiver 是*T,你可以在一个 T 类型的实例变量 V 上面调用这个

method,而不需要&V 去调用这个 method

如果一个 method 的 receiver 是 T,你可以在一个*T 类型的变量 P 上面调用这个 method,

而不需要 *P 去调用这个 method



method继承

如果匿名字段实现了一个 method,那么包含这个匿名字段的 struct 也能调用该

method。

type Human struct {

	name string

	age int

	phone string

}

type Student struct {

	Human //匿名字段

	school string

}



func (h *Human) SayHi() {

	fmt.Printf("Hi, I am %s you can call me on %s\n", h.name, 

	h.phone)

}

mark := Student{Human{"Mark", 25, "222-222-YYYY"}, "MIT"}

mark.sayHi()



method重写



func (h *Human) SayHi() {

	fmt.Printf("Hi, I am %s you can call me on %s\n", h.name, h.phone)

}

//Employee 的 method 重写 Human 的 method

func (e *Employee) SayHi() {

	fmt.Printf("Hi, I am %s, I work at %s. Call me on %s\n", e.name,

	e.company, e.phone) //Yes you can split into 2 lines here.

}

  

你可能感兴趣的:(Go)