相同问题go语言与php的实现对比
一、面向对象
php:
classRectangle{private$width;private$height;private$color;publicfunction__construct($width,$height,$color){$this->width=$width;$this->height=$height;$this->color=$color;}publicfunctionsetColor($color){$this->color=$color;}publicfunctiongetColor(){return$this->color;}publicfunctionarea(){return$this->width*$this->height;}}$r1=newRectangle(12,2,"白色");$r2=newRectangle(9,4,"蓝色");echo"Areaofr1is".$r1->area()."\n";echo"Areaofr2is".$r2->area()."\n";echo"Colorofr2is".$r2->getColor()."\n";echo"setnewcolor\n";$r2->setColor("绿色");echo"Colorofr2is".$r2->getColor()."\n";
go:
packagemainimport"fmt"typeRectanglestruct{width,heightfloat64colorstring}//如果声明接收者为指定,当使用T类型来调用时,go会自动转换为*T,太TM聪明了func(r*Rectangle)SetColor(colorstring){r.color=color}func(rRectangle)area()float64{returnr.width*r.height}funcmain(){r1:=Rectangle{12,2,"白色"}r2:=Rectangle{9,4,"蓝色"}fmt.Println("Areaofr1is:",r1.area())fmt.Println("Areaofr2is:",r2.area())fmt.Println("Colorofr2is:",r2.color)fmt.Println("setnewcolor")r2.SetColor("绿色")//等价于(&r2).SetColor("绿色"),这里r2不需要传地址,当然,传地址也不错,只是go会自动帮助转换,没有必要fmt.Println("Colorofr2is:",r2.color)}
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。