golang OOP面向对象

摘自:http://www.01happy.com/golang-oop/

golang中并没有明确的面向对象的说法,实在要扯上的话,可以将struct比作其它语言中的class。

类声明

1
2
3
4
5
type Poem struct {
    Title  string
    Author string
    intro  string
}

这样就声明了一个类,其中没有public、protected、private的的声明。golang用另外一种做法来实现属性的访问权限:属性的开头字母是大写的则在其它包中可以被访问,否则只能在本包中访问。类的声明和方法亦是如此。

类方法声明

1
2
3
func (poem *Poem) publish() {
    fmt.Println("poem publish")
}

或者

1
2
3
func (poem Poem) publish() {
    fmt.Println("poem publish")
}

和其它语言不一样,golang声明方法和普通方法一致,只是在func后增加了poem *Poem这样的声明。加*和没有加*的区别在于一个是传递指针对象,一个是传递值对象。

实例化对象

实例化对象有好几种方式

1
2
3
4
5
6
7
8
poem := &Poem{}
poem.Author = "Heine"
poem2 := &Poem{Author: "Heine"}
poem3 := new(Poem)
poem3.Author = "Heine"
poem4 := Poem{}
poem4.Author = "Heine"
poem5 := Poem{Author: "Heine"}

实例化的时候可以初始化属性值,如果没有指明则默认为系统默认值

加&符号和new的是指针对象,没有的则是值对象,这点和php、java不一致,在传递对象的时候要根据实际情况来决定是要传递指针还是值。

tips:当对象比较小的时候传递指针并不划算。

构造函数

查看官方文档,golang并没有构造函数一说。如果一定要在初始化对象的时候进行一些工作的话,可以自行封装产生实例的方法。

1
func NewPoem(param string, p ...interface{}) *Poem

示例:

1
2
3
4
5
6
7
func NewPoem(author string) (poem *Poem) {
    poem = &Poem{}
    poem.Author = author
    return
}
 
poem6 := NewPoem("Heine")
原文地址:https://www.cnblogs.com/bonelee/p/6592129.html