您好,登錄后才能下訂單哦!
一、面向對象
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) }
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。