一、面向对象
php:
class聽Rectangle { 聽聽聽聽private聽$width; 聽聽聽聽private聽$height; 聽聽聽聽private聽$color; 聽聽聽聽public聽function聽__construct($width,聽$height,聽$color) 聽聽聽聽{ 聽聽聽聽聽聽聽聽$this->width聽聽=聽$width; 聽聽聽聽聽聽聽聽$this->height聽=聽$height; 聽聽聽聽聽聽聽聽$this->color聽聽=聽$color; 聽聽聽聽} 聽聽聽聽public聽function聽setColor($color) 聽聽聽聽{ 聽聽聽聽聽聽聽聽$this->color聽=聽$color; 聽聽聽聽} 聽聽聽聽public聽function聽getColor() 聽聽聽聽{ 聽聽聽聽聽聽聽聽return聽$this->color; 聽聽聽聽} 聽聽聽聽public聽function聽area() 聽聽聽聽{ 聽聽聽聽聽聽聽聽return聽$this->width聽*聽$this->height; 聽聽聽聽} } $r1聽=聽new聽Rectangle(12,聽2,聽"白色"); $r2聽=聽new聽Rectangle(9,聽4,聽"蓝色"); echo聽"Area聽of聽r1聽is聽".聽$r1->area()."\n"; echo聽"Area聽of聽r2聽is聽".聽$r2->area()."\n"; echo聽"Color聽of聽r2聽is聽".聽$r2->getColor()."\n"; echo聽"set聽new聽color\n"; $r2->setColor("绿色"); echo聽"Color聽of聽r2聽is聽".聽$r2->getColor()."\n";
go:
package聽main import聽"fmt" type聽Rectangle聽struct聽{ width,聽height聽float64 color聽聽聽聽聽聽聽聽聽string } //聽如果声明接收者为指定,当使用T类型来调用时,go会自动转换为*T,太TM聪明了 func聽(r聽*Rectangle)聽SetColor(color聽string)聽{ r.color聽=聽color } func聽(r聽Rectangle)聽area()聽float64聽{ return聽r.width聽*聽r.height } func聽main()聽{ r1聽:=聽Rectangle{12,聽2,聽"白色"} r2聽:=聽Rectangle{9,聽4,聽"蓝色"} fmt.Println("Area聽of聽r1聽is:聽",聽r1.area()) fmt.Println("Area聽of聽r2聽is:聽",聽r2.area()) fmt.Println("Color聽of聽r2聽is:聽",聽r2.color) fmt.Println("set聽new聽color") r2.SetColor("绿色")聽//聽等价于(&r2).SetColor("绿色"),这里r2不需要传地址,当然,传地址也不错,只是go会自动帮助转换,没有必要 fmt.Println("Color聽of聽r2聽is:聽",聽r2.color) }