Golang Getting Started Series 5: object-oriented in GO language

I talked a lot about the basics of the Go language, including the installation of the go environment, the syntax of the go language, etc. If you are interested, you can read the previous article first. http://quickintro123.com/index.php/category/golang/

Object-oriented in GO

In fact, GO is not a pure object-oriented programming language. It does not provide the class keyword, only the struct type.

In java or C#, structs cannot have member functions. However, structs in Go can have "member functions". Methods can be added to structures, similar to the implementation of a class.

I personally think that the object-oriented of the Go language is actually simpler and easier to understand.

Anyone who has learned java or C# should know the three basic characteristics of object orientation: encapsulation, inheritance, and polymorphism. I will not elaborate on their definition here. Let ’s take a look at how object-oriented is implemented in the Go language.

1. Encapsulation Features

Golang's mechanism to distinguish between public and private properties is whether the method or property has a capital letter. If the method with a capital letter is public, if it has a lowercase letter, it is private.

package main

import "fmt"

type Person struct {
    name string
}

func (person *Person) setName(name string) {
    person.name = name
}

func (person *Person) GetInfo() {
    fmt.Println(person.name)
}

func main() {
    p := Person{"zhangsan"}
    p.setName("lisi")
    p.GetInfo()
}

2. Inheritance

The inheritance method of the GO language uses an anonymous combination: The Woman structure contains the anonymous field Person, so the attributes in Person also belong to the Woman object.

package main

import "fmt"

type Person struct {
    name string
}

type Woman struct {
    Person
    sex string
}

func main() {
    woman := Woman{Person{"wangwu"}, "woman"}
    fmt.Println(woman.name)
    fmt.Println(woman.sex)
}

  

3. Polymorphic feature

package main

import "fmt"

type Eater interface {
    Eat()
}

type Man struct {
}

type Woman struct {
}

func (man *Man) Eat() {
    fmt.Println("Man Eat")
}

func (woman *Woman) Eat() {
    fmt.Println("Woman Eat")
}

func main() {
    var e Eater

    woman := Woman{}
    man := Man{}

    e = &woman
    e.Eat()

    e = &man
    e.Eat()
}

Finally

In the above, I briefly introduced how to implement object orientation in Go language. In fact, it is similar to java and C#. You can compare them. In summary: Go has no classes, but loosely coupled types and methods to implement the interface.

This entry was posted in development, golang and tagged , , . Bookmark the permalink.

One Response to Golang Getting Started Series 5: object-oriented in GO language

  1. Like!! Great article post.Really thank you! Really Cool.

Leave a Reply

Your email address will not be published. Required fields are marked *