Go學習筆記-面向對象struct成員變量

結構體struct能夠用來描述一組數據值,這組值的本質便可以是原始的,也能夠是非原始的。是用戶自定義的類型,它表明若干字段的集合,能夠用於描述一個實體對象,相似javaphp中的class,是golang面向對象編程的基礎類型。
今天咱們先來看看golang中的成員變量的實現。php

基本的屬性(成員變量)
type Teacher struct {  
  Name string  
  age int  
  Sex string
}  
func Create() Teacher {  
   cang := Teacher{Name:"teacher cang",age:20,Sex:"woman"}  
   return cang  
}

對於在上面結構體teacher其實咱們能夠把它當作一個className,Sex是能夠被外部(其餘的包)訪問的公有變量,而age則只能在包內部被訪問。java

Method(成員方法)
type Student struct {  
  Name string  
  Sex string  
  Age int  
}  
func (student *Student) SetName(name string)  {  
   student.Name = name  
}  
func (student *Student) GetName() string {  
   return student.Name  
}  
func XiaoPeng()  {  
   xiaoPeng := Student{}  
   xiaoPeng.SetName("xiao peng")  
   fmt.Println(xiaoPeng.GetName()) //xiao peng  
}

golang中爲struct聲明成員方法,只須要在func指定當前func屬於的struct便可。
上面能夠看到咱們在指定struct的時候,傳入的是一個指針。那麼可不能夠不傳指針呢?固然是能夠的,可是這個時候咱們獲得的是一個原結構體的一個副本。golang

type Student struct {  
  Name string  
  Sex string  
  Age int  
}  
func (student Student) SetAge(number int)  {  
   student.Age = number  
  fmt.Println(student.Age)  //21
}  
  
func (student *Student) GetAge() int {  
   return student.Age  
}  
func XiaoPeng()  {  
   xiaoPeng := Student{}  
   xiaoPeng.SetAge(21)  
   fmt.Println(xiaoPeng.GetAge()) //0   
}

能夠看到若是在SetAge內部是能夠訪問當前的age賦值。可是在外部是獲取不到age的值的。其實在SetAge中是對xiaoPeng的一個副本拷貝複製,至關於值傳遞編程

期待一塊兒交流

qrcode_for_gh_60813539dc23_258.jpg

相關文章
相關標籤/搜索