美文网首页
GO语言基础(九)-面向对象

GO语言基础(九)-面向对象

作者: 87d6dc4b11a7 | 来源:发表于2022-01-27 16:03 被阅读0次

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())
    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的名字一模一样,但是如果接收者不一样,那么method就不一样
  • method里面可以访问接收者的字段
  • 调用method通过.访问,就像struct里面访问字段一样

可以在任何的自定义类型中定义任意多的method,接下来让我们看一个复杂一点的例子

package main

import "fmt"

const(
    WHITE = iota
    BLACK
    BLUE
    RED
    YELLOW
)

type Color byte

type Box struct {
    width, height, depth float64
    color Color
}

type BoxList []Box //a slice of boxes

func (b Box) Volume() float64 {
    return b.width * b.height * b.depth
}

func (b *Box) SetColor(c Color) {
    b.color = c
}

func (bl BoxList) BiggestColor() Color {
    v := 0.00
    k := Color(WHITE)
    for _, b := range bl {
        if bv := b.Volume(); bv > v {
            v = bv
            k = b.color
        }
    }
    return k
}

func (bl BoxList) PaintItBlack() {
    for i := range bl {
        bl[i].SetColor(BLACK)
    }
}

func (c Color) String() string {
    strings := []string {"WHITE", "BLACK", "BLUE", "RED", "YELLOW"}
    return strings[c]
}

func main() {
    boxes := BoxList {
        Box{4, 4, 4, RED},
        Box{10, 10, 1, YELLOW},
        Box{1, 1, 20, BLACK},
        Box{10, 10, 1, BLUE},
        Box{10, 30, 1, WHITE},
        Box{20, 20, 20, YELLOW},
    }

    fmt.Printf("We have %d boxes in our set\n", len(boxes))
    fmt.Println("The volume of the first one is", boxes[0].Volume(), "cm³")
    fmt.Println("The color of the last one is",boxes[len(boxes)-1].color.String())
    fmt.Println("The biggest one is", boxes.BiggestColor().String())

    fmt.Println("Let's paint them all black")
    boxes.PaintItBlack()
    fmt.Println("The color of the second one is", boxes[1].color.String())

    fmt.Println("Obviously, now, the biggest one is", boxes.BiggestColor().String())
}

上面的代码通过const定义了一些常量,然后定义了一些自定义类型

  • Color作为byte的别名
  • 定义了一个struct:Box,含有三个长宽高字段和一个颜色属性
  • 定义了一个slice:BoxList,含有Box
    然后以上面的自定义类型为接收者定义了一些method
  • Volume()定义了接收者为Box,返回Box的容量
  • SetColor(c Color),把Box的颜色改为c
  • BiggestColor()定在在BoxList上面,返回list里面容量最大的颜色
  • PaintItBlack()把BoxList里面所有Box的颜色全部变成黑色
  • String()定义在Color上面,返回Color的具体颜色(字符串格式)

指针作为receiver

如果一个method的receiver是*T,你可以在一个T类型的实例变量V上面调用这个method,而不需要&V去调用这个method
如果一个method的receiver是T,你可以在一个*T类型的变量P上面调用这个method,而不需要*P去调用这个method

method继承

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

package main

import "fmt"

type Human struct {
    name string
    age int
    phone string
}

type Student struct {
    Human //匿名字段
    school string
}

type Employee struct {
    Human //匿名字段
    company string
}

//在human上面定义了一个method
func (h *Human) SayHi() {
    fmt.Printf("Hi, I am %s you can call me on %s\n", h.name, h.phone)
}

func main() {
    mark := Student{Human{"Mark", 25, "222-222-YYYY"}, "MIT"}
    sam := Employee{Human{"Sam", 45, "111-888-XXXX"}, "Golang Inc"}

    mark.SayHi()
    sam.SayHi()
}

method重写

上面的例子中,如果Employee想要实现自己的SayHi,怎么办?简单,和匿名字段冲突一样的道理,我们可以在Employee上面定义一个method,重写匿名字段的方法。请看下面的例子

package main

import "fmt"

type Human struct {
    name string
    age int
    phone string
}

type Student struct {
    Human //匿名字段
    school string
}

type Employee struct {
    Human //匿名字段
    company string
}

//Human定义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.
}

func main() {
    mark := Student{Human{"Mark", 25, "222-222-YYYY"}, "MIT"}
    sam := Employee{Human{"Sam", 45, "111-888-XXXX"}, "Golang Inc"}

    mark.SayHi()
    sam.SayHi()
}

相关文章

  • GO语言基础(九)-面向对象

    method method的语法如下: 在使用method的时候重要注意几点: 虽然method的名字一模一样,但...

  • 001-python知识

    Python基础 一、Python的基本概念 (一)面向对象 Python是一门面向对象的语言,像C语言和GO语言...

  • 第十六章:Go语言面向对象编程

    1. GO语言OOP概述 Go语言不是纯粹的面向对象的语言,准确是描述是,Go语言支持面向对象编程的特性.Go语言...

  • Go基础语法(十二)

    面向对象编程 Go 并不是完全面向对象的编程语言。 Go 官网的 FAQ 回答了 Go 是否是面向对象语言,摘录如...

  • struct

    面向对象编程 Go支持面向对象编程特性,但和传统面向对象编程是有区别的,Go并不是纯粹的面向对象语言。 Go没有类...

  • Go 语言程序设计——过程式编程(1)

    Go 语言可以用于写纯过程式程序,用于写面向对象程序,也可以用于写过程式和面向对象相结合的程序 语句基础 Go 语...

  • go day06 面向对象 匿名组合 方法、方法集、方法

    面向对象 对于面向对象编程的支持Go语言设计的非常简洁而优雅。因为,Go语言并没有沿袭传统的面向对象编程中的诸多概...

  • 【Golang 基础】Go 语言 面向对象

    Go 语言的面向对象   Go 语言的面向对象非常简单,仅支持封装,不支持继承和多态。继承和多态是在接口中实现的。...

  • 第13章-OOP面向对象编程

    面向对象(OOP) go并不是一个纯面向对象的编程语言。在go中的面向对象,结构体替换了类。 Go并没有提供类cl...

  • Golang(十三) OOP面向对象编程

    面向对象(OOP) go并不是一个纯面向对象的编程语言。在go中的面向对象,结构体替换了类。 Go并没有提供类cl...

网友评论

      本文标题:GO语言基础(九)-面向对象

      本文链接:https://www.haomeiwen.com/subject/cvuwhrtx.html