golang struct

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.{屬性} 
}
//執行結果:
the Rectangle width: 20

2、給結構體定義方法

package main

import "fmt"

type Rectangle struct {
	width float64
	height float64
}

func (r *Rectangle) area() float64 { //定義一個area的函數,返回值類型爲float64,函數的接收者爲前面括號的(變量名 類型名)
	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函數
}
//執行結果:
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) //打印結果
}
//執行結果:
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)
}
//執行結果:
the Rectangle width: 20
the area of Rectangle:  200
the Rectangle width: 30                 //結果顯示已經改變了width的值


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章