type Vertex struct{
X,Y float64
}
func (v vertex)Abs()float64{
return math.Sqrt(v.X*v.X+v.Y*v.Y)
}//Abs方法的接受者为v,类型为Vertex
func main (){
v:=Vertex{3,4}
}
fmt.Println(v.Abs())//输出为5
func Abs(v Vertex)float64{
return math.Sqrt(v.X*v.X+v.Y*v.Y)
}
type MyFloat float64
func (f MyFloat)Abs()float64{//带 Abs 方法的数值类型 MyFloat。
if(f<0)
return float64(-f)
else
return float64(f)
}
type Vertex struct {
X,Y float64
}
func (v*Vertex)Abs(f float64){
v.X=v.X*f
v.Y=v.Y*f
}
使用指针作为接收者的原因
type Abser interface{
Abs()float64
}
func main (){
var a Abser
f:=MyFloat(-math.Sqrt2)
v:=Vertex{3,4}
a=f//a MyFloat实现了Abser
a=&v//*Vertex实现了Abser
}
type I interface{
M()
}
type T struct {
string S
}
// 此方法表示类型 T 实现了接口 I,但我们无需显式声明此事。
func (t T)M(){
fmt.Piintln(t.S)
}
func main (){
var i I=T{"hello"}
i.M()
}
type I interface{//定义接口类型
M()
}
type T struct{
string S
}
func (t*T)M(){//方法M
fmt.Printf(t.S)
}
type F float64
func(f F)M(){//f作为方法M()的接收者
fmt.Println(f)
}
func main (){
var i I//接口类型变量i
i=&T{"hello"}
describe(i)//接口值作为函数的参数
i.M()//接口值调用方法,与此同时,会执行其底层类型的同名方法
func describe(i I) {
fmt.Printf("(%v, %T)\n", i, i)
}
}
func (t*T)M(){
if(t==nil){
fmt.Println("<nil>")
return
}
fmt.Println(t.S)
}
interface{}
t:=i.(T)
t,ok:=i(T)
func main (){
var i interface{}="hello"
s:=i.(string)
s,ok:=i.(string)
}
switch v:=i.(type){
case T://V的类型为T
case S:
default:
}
type Stringer interface{
String()string
}
type person struct {
Name String
Age int
}
func (p person) String () stirng{
return fmt.Sprintf("%v,(%v years)",P.Name,P.Age)
}
func main (){
a:=person{"bob",32}
b:=person{"tom",12}
fmt.Println(a,b)
}
type error interface{
Error()string
}
func (T)Read(b[]byte)(n int err error)
package image
type Image interface{
ColorModel()color.Model
Bounds()Rectangle
At(x,y int)color.Color
}
import (
"fmt"
"image"
)
func main() {
m := image.NewRGBA(image.Rect(0, 0, 100, 100))
fmt.Println(m.Bounds())
fmt.Println(m.At(0, 0).RGBA())
}