go语言圣经第六章(读书笔记)

时间:2019-07-24 19:38:33   收藏:0   阅读:98

第六章 方法

方法声明

type Point struct{ X, Y float64 }
// traditional function
func Distance(p, q Point) float64 {
    return math.Hypot(q.X-p.X, q.Y-p.Y)
}
// same thing, but as a method of the Point type
func (p Point) Distance(q Point) float64 {
    return math.Hypot(q.X-p.X, q.Y-p.Y)
}

p := Point{1, 2}
q := Point{4, 6}
fmt.Println(Distance(p, q)) // "5", function call
fmt.Println(p.Distance(q))
// "5", method call

基于指针对象的方法

func (p *Point) ScaleBy(factor float64) {
    p.X *= factor
    p.Y *= factor
}

Nil也是一个合法的接收器类型

// An IntList is a linked list of integers.
// A nil *IntList represents the empty list.
type IntList struct {
    Value int
    Tail
    *IntList
}
// Sum returns the sum of the list elements.
func (list *IntList) Sum() int {
    if list == nil {
        return 0
    }
    return list.Value + list.Tail.Sum()
}

通过嵌入结构体来扩展类型

package main

import (
  "fmt"
)

type Point struct{ X, Y float64 }

func (p *Point) ins() {
  p.X++
  p.Y++
}


type ColoredPoint struct {
  Point
  Color string
}

func main() {
    cp := &ColoredPoint{
      Point: Point{X: 5, Y:6},
      Color: "red",
    }

  cp.ins()
  fmt.Println(cp)

}
package main

import (
  "fmt"
)

type Point struct{ X, Y float64 }

func (p *Point) ins() {
  p.X++
  p.Y++
}


type ColoredPoint struct {
  *Point
  Color string
}

func main() {
  cp := &ColoredPoint{
    &Point{X: 5, Y:6},
    "red",
  }

  cp.ins()
  fmt.Println(cp)
  fmt.Println(cp.Point)
  fmt.Println(cp.X)
  fmt.Println(cp.Y)
  fmt.Println(cp.Color)

}

方法值

p := Point{1, 2}
q := Point{4, 6}
distanceFromP := p.Distance // method value
fmt.Println(distanceFromP(q)) // "5"
var origin Point // {0, 0}
fmt.Println(distanceFromP(origin)) // "2.23606797749979", sqrt(5)
scaleP := p.ScaleBy // method value
scaleP(2) // p becomes (2, 4)
scaleP(3) // then (6, 12)
scaleP(10) // then (60, 120)
type Rocket struct { /* ... */ }
func (r *Rocket) Launch() { /* ... */ }
r := new(Rocket)
time.AfterFunc(10 * time.Second, func() { r.Launch() })
//上下等价
time.AfterFunc(10 * time.Second, r.Launch)

封装

原文:https://www.cnblogs.com/laiyuanjing/p/11240216.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!