22

Go学习笔记-面向对象struct成员变量

 4 years ago
source link: https://studygolang.com/articles/25684
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

结构体 struct 可以用来描述一组数据值,这组值的本质即可以是原始的,也可以是非原始的。是用户自定义的类型,它代表若干字段的集合,可以用于描述一个实体对象,类似 javaphp 中的 class ,是 golang 面向对象编程的基础类型。

今天我们先来看看 golang 中的成员变量的实现。

基本的属性(成员变量)

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 则只能在包内部被访问。

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 的时候,传入的是一个指针。那么可不可以不传指针呢?当然是可以的,但是这个时候我们得到的是一个原结构体的一个副本。

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 的一个副本拷贝复制,相当于 值传递

期待一起交流

Y3yu63Z.jpg!web


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK