struct
1、定義一個struct
package main import "fmt" type Rectangle struct { width float64 height float64 } func main(){ var r Rectangle //聲明一個結構體 r,width height的值為“零”值。在這里為0.0,0.0 r = Rectangle{width:20,height:10} //給長寬賦值,帶名稱時,順序隨意 r = Rectangle{20,10} //等價上部的賦值,不帶變量名稱時,值與聲明的變量順序一致。 fmt.Println("the Rectangle width:",r.width) // 訪問 r.{屬性} } //執(zhí)行結果: the Rectangle width: 20
2、給結構體定義方法
package main import "fmt" type Rectangle struct { width float64 height float64 } func (r *Rectangle) area() float64 { //定義一個area的函數(shù),返回值類型為float64,函數(shù)的接收者為前面括號的(變量名 類型名) return r.width * r.height } func main(){ var r Rectangle r = Rectangle{width:20,height:10} r = Rectangle{20,10} fmt.Println("the Rectangle width:",r.width) fmt.Println("the area of Rectangle: ",r.area()) //直接調用area函數(shù) } //執(zhí)行結果: the Rectangle width: 20 the area of Rectangle: 200 //計算結果為200
3、結構體方法接收類型為指針,則能改變原結構體的屬性值
我們先將類型設置為值類型看看
package main import "fmt" type Rectangle struct { width float64 height float64 } func (r *Rectangle) area() float64 { return r.width * r.height } func (r Rectangle) changeWidth(){ //把接收體的類型設置為值類型 r.width = 30 } func main(){ var r Rectangle r = Rectangle{width:20,height:10} r = Rectangle{20,10} fmt.Println("the Rectangle width:",r.width) fmt.Println("the area of Rectangle: ",r.area()) r.changeWidth() //改變了width fmt.Println("the Rectangle width:",r.width) //打印結果 } //執(zhí)行結果: the Rectangle width: 20 the area of Rectangle: 200 the Rectangle width: 20 //結果顯示并沒有改變
我們將接收體設置為指針
package main import "fmt" type Rectangle struct { width float64 height float64 } func (r *Rectangle) area() float64 { return r.width * r.height } func (r *Rectangle) changeWidth(){ // 指針類型 r.width = 30 } func main(){ var r Rectangle r = Rectangle{width:20,height:10} r = Rectangle{20,10} fmt.Println("the Rectangle width:",r.width) fmt.Println("the area of Rectangle: ",r.area()) r.changeWidth() fmt.Println("the Rectangle width:",r.width) } //執(zhí)行結果: the Rectangle width: 20 the area of Rectangle: 200 the Rectangle width: 30 //結果顯示已經(jīng)改變了width的值
另外有需要云服務器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內外云服務器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務器、裸金屬服務器、高防服務器、香港服務器、美國服務器、虛擬主機、免備案服務器”等云主機租用服務以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務可用性高、性價比高”等特點與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應用場景需求。
文章題目:golangstruct-創(chuàng)新互聯(lián)
本文網(wǎng)址:http://aaarwkj.com/article44/ccjshe.html
成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供云服務器、網(wǎng)站排名、外貿(mào)網(wǎng)站建設、響應式網(wǎng)站、定制開發(fā)、App開發(fā)
聲明:本網(wǎng)站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經(jīng)允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內容