Chapter Four, Go- "Object-oriented"

Chapter 4. Go- "Object-oriented"

4.1. Structure and method

(1) Object-oriented of go language

  • go only supports encapsulation, does not support inheritance and polymorphism
  • Go language has no class, only struct

(2) The creation of struct

package main

import "fmt"

func main() {
	type treeNode struct {
		value int
		left, right *treeNode//Pointer type
	}
	//Regardless of the address or the result itself, use "." to access members
	var root treeNode//root is an instance
	root = treeNode{value: 3}
	fmt.Println(root)//{3 <nil> <nil>}

	root.left = &treeNode{}
	fmt.Println(root)//{3 0x1104c0f0 0x1104c100}
}

(3) Create a method for struce

package main

import "fmt"

type treeNode struct {
	value int
}

//Create a method for the structure
func (node ​​treeNode) print() {
	fmt.Println(node.value)
}

func main() {
	var root treeNode
	root = treeNode{value: 3}
	root.print()//3
}

(4) Use the pointer as the method receiver to change the structure content

package main

import "fmt"

type treeNode struct {
	value int
}

//Create a method for the structure
func (node ​​treeNode) print() {
	fmt.Println(node.value)
}

//If the pointer "*treeNode" is not applicable, the value of value cannot be changed
//func (node ​​treeNode) setValue(value int) {
//node.value = value
//}


//Only use only pointers to change the structure content
func (node ​​*treeNode) setValue(value int) {
	node.value = value
}

func main() {
	var root treeNode
	root = treeNode{value: 3}
	root.print()//3
	root.setValue(6)
	root.print()//6
}

4.2. Packages and Encapsulation

(1) Package

  • Capitalize the first letter: public
  • Initial lowercase: private

(2 bags

  • One package per directory
  • The main package contains executable entry
  • The method defined for the structure must be placed in the same package
  • Can be different files
Reference: https://cloud.tencent.com/developer/article/1481075 Chapter 4, Go-"Object-oriented"-Cloud + Community-Tencent Cloud