Go-22-方法

方法

Go语言同时有函数和方法,方法的本质是函数,但是方法和函数又有所不同。

函数(function)是一段具有独立功能的代码,可以被反复多次调用,从而实现代码复用。

方法(method)是一个类的行为功能,只有该类的对象才能调用。

定义:

func(接收者  接收者类型)方法名(参数列表)(返回值列表){
// 方法体
}

接受者中的变量在命名时,官方建议使用接受者类型的第一个小写字母。

package main

import "fmt"

type Flowers struct {
    name string
    color string
}
func main() {
    f1:=Flowers{"红玫瑰",""}
    f1.printFlower()
    printFlower(f1)
}
//方法
func (f Flowers) printFlower()  {
    fmt.Println(f)
}
//函数
func printFlower(f Flowers){
    fmt.Println(f)
}

使用方法的原因:

  • Go不是一种纯粹面向对象的编程语言,它不支持类。因此其方法旨在实现类似于类的行为。
  • 相同名称的方法可以在不同的类型上定义,而具有相同名称的函数是不允许的。

方法的继承

方法是可以继承的,如果匿名字段实现了一个方法,那么包含这个匿名字段的struct也能调用该匿名字段中的方法

package main

import "fmt"

// 方法的继承
type Human struct {
    name string
    age int
}
type Students struct {
    Human //匿名对象
    class string
}
type Teachers struct {
    Human// 匿名对象
    address string
}
func main() {
    s:=Students{Human{"xiaoming",18}, "Senior one"}
    s.print()
}
func (h *Human)print()  {
    fmt.Println(h)
}

方法的重写

在Go语言中,方法重写是指一个包含了匿名字段的struct也实现了该匿名字段实现的方法。

package main

import "fmt"

// 方法的继承
type Human struct {
    name string
    age int
}
type Students struct {
    Human //匿名对象
    class string
}
type Teachers struct {
    Human// 匿名对象
    address string
}
func main() {
    s:=Students{Human{"xiaoming",18}, "Senior one"}
    s.print()
}
func (h *Human)print()  {
    fmt.Println(h)
}
func (s *Students) print(){
    fmt.Println(s)
}

 

posted @ 2020-05-29 09:28  sixinshuier  阅读(117)  评论(0编辑  收藏  举报