結構體struct
能夠用來描述一組數據值,這組值的本質便可以是原始的,也能夠是非原始的。是用戶自定義的類型,它表明若干字段的集合,能夠用於描述一個實體對象,相似java
,php
中的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
其實咱們能夠把它當作一個class
而Name
,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
的一個副本拷貝複製,至關於值傳遞
。編程