Error in user YAML: (<unknown>): found character that cannot start any token while scanning for the next token at line 5 column 1
---
title: go-basic-方法
copyright: true
date: 2019-12-12 10:35:40
tags:
- go
- go-basic
- go-basic-方法
categories:
- go
description:
---
方法和函数相比,多个接收器(receiver)
package geometry
import "math"
//Point 是对二维平面的点的抽象
type Point struct{
X,Y float64
}
//Distance 计算两个点的距离
func Distance(p,q Point) float64 {
return math.Hypot(q.X-p.X,q.Y-p.Y)
}
//Distance 计算两个点的距离
func (p Point) Distance(q Point) float64{
return math.Hypot(q.X-p.X,q.Y-p.Y)
}
r := &Point{1,2}
b := &Point{2,4}
d := r.Distance(b)
type List struct{
Value int
Tail *List
}
//Sum 返回list的所有value的和
func (list *List) Sum() int{
if list == nil{
return 0
}
return list.Value + list.Tail.Sum()
}
嵌套的结构体的方法没有二义性,就可以直接调用,有的话需要详细到某个成员
type ColorPoint struct{
Point
Color color.RGBA
}
p := ColorPoint{Point{1,2},color.RGBA{23,34,45,100}}
d := p.Distance(p)
DistanceFromP := p.Distance
//调用
DistanceFromP(q)
==========いざ、ここまで==========*´∀)´∀
)*´∀)*´∀
)======================