Golang(筆記) 面向對象


package main 

import (
"fmt"
)
//對象定義
type Rect struct{
x,y float64
width ,height float64
} 
//對象方法實現
func (r *Rect) Area()float64{
return r.width*r.height
}
//Go語言沒有構造函數的概念
//對象的創建通常交由一個全局的創建函數NewXXX來命名 標識構造函數
func NewRect(x,y,width,height float64) *Rect{
return &Rect{x,y,width,height}
}
//Go 也提供了繼承 但是采用了組合的文法 稱之為匿名組合
//匿名組合  示例

type Base struct{
Name string
}
func (base *Base) Foo(){
base.Name="Base Foo2"
}
func (base *Base)Bar(){
base.Name="Base Bar"
} 
type Foo struct{
Base
Name1 string
}
func (foo *Foo) Bar(){
foo.Base.Bar()
}

func main() {
rect:=new(Rect)
rect1:=&Rect{width:109,height:10}
rect2:=&Rect{1,2,3,4}
rect.width=19.9
rect.height=22.1
foo:=&Foo{}
foo.Foo();
fmt.Println(foo.Name)
fmt.Println(rect.Area())
fmt.Println(rect1.Area())
fmt.Println(rect2.Area())
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM