Go language Development (iv), go language object-oriented

Source: Internet
Author: User

Go language Development (iv), go language object-oriented one, structure and method 1, the definition of the structure of the body

You can define different data types for different items in a struct.
A struct is a collection of data consisting of a series of data of the same type or different types.
struct definitions require the use of type and struct statements. A struct statement defines a new data type in which the struct has one or more members. The Type statement sets the name of the struct body. The format of the struct is as follows:

type struct_variable_type struct {   member definition;   member definition;   ...   member definition;}

struct types are used in the syntax format for variable declarations:
variable_name := structure_variable_type {value1, value2...valuen}
The data structure of the binary tree node is defined as follows:

package mainimport "fmt"type TreeNode struct{   Value int   Left,Right *TreeNode}func main() {   var root TreeNode   fmt.Println(root)}
2. Access of struct members

If you want to access struct members, you need to use the dot number (.) operator, in the form: "struct. Member name".
struct type variables are defined using the struct keyword, with the following examples:

func main() {   var root TreeNode   root.Value = 0   root.Left = &TreeNode{Value:1}   root.Right = &TreeNode{2,nil,nil}   root.Left.Left = &TreeNode{Value:3}   root.Print()}
3. Definition of Structure method

The struct method definition is outside the scope of the struct and requires the recipient to be specified in the function declaration.

func (variable_name struct_variable_type) function_name(parameters){    //函数体}

such as the traversal of the binary tree node printing function is as follows:

func (node TreeNode) Print(){      fmt.Println(node.Value, " ")}func (node *TreeNode)traverse(){   if node != nil{      //递归遍历左子树      node.Left.traverse()      node.Print()      //递归遍历右子树      node.Right.traverse()   }}
4, the structure of the pointer

If the value of a struct member needs to be modified in a struct's method, the struct pointer must be used as the recipient of the method. If the structure is too large, consider using the struct pointer as the recipient of the method. Both the value receiver and the pointer receiver can receive the value and the pointer-passed struct body.
The nil pointer can also invoke the method.

package mainimport (   "fmt")type TreeNode struct{   Value int   Left,Right *TreeNode}func createTreeNode(value int) *TreeNode{   return &TreeNode{Value:value}}func (node TreeNode) Print(){      fmt.Println(node.Value, " ")}func (node *TreeNode)traverse(){   if node != nil{      //递归遍历左子树      node.Left.traverse()      node.Print()      //递归遍历右子树      node.Right.traverse()   }}func (node *TreeNode)setValue(value int){   if node!= nil{      node.Value = value   }else {      fmt.Println("The node is nil.")   }}func main() {   var root TreeNode   root.Value = 0   root.Left = &TreeNode{Value:1}   root.Right = &TreeNode{2,nil,nil}   root.Left.Left = &TreeNode{Value:3}   root.traverse()   root.setValue(100)   root.traverse()   }
Two, package and package 1, Package introduction

Packages are used to organize go source code, providing better reusability and readability. Because the package provides the encapsulation of the code, it makes the go application easy to maintain.
The go Language object-oriented only supports encapsulation, and does not support inheritance and polymorphism.
The go language uses the CamelCase naming method to name the function, the first letter of the function name is public, and lowercase indicates private.
Access rights are for packages, and each directory in the Go language is a package, and the package name and directory name can be different. If there is a main function under the directory, the directory can have only one main package, and the main package contains executable portals.
The method defined for a struct must be within a package, but it can be a different file.

2, the definition of the package

All executable go programs must contain a main function as the entry for the program to run. The main function should be placed in the main package.
The package definition syntax is as follows:
package packagename
Specifies that a source file belongs to a package and should be placed on the first line of each source file.
The syntax for importing an existing package is as follows:
import "packagename"?
The source files that belong to a package should be placed in a separate named folder. In accordance with the custom of the go language, you should name the package folder with the package name.
In the PackageName folder, all files begin with the package PackageName, because all the files in the folder go language files belong to the PackageName pack.

3, the import of the package

In order to use the custom package, you must first import the package. The syntax for importing a custom package is import path. You must specify a relative path to the custom package relative to the? src folder in the workspace.
It is illegal to import a package in the go language without using the package in the code. In the program development phase, the package is often imported first, but not used, can you use a blank identifier? .
var
= Packagename.method code can mask errors.
If you import a package only to ensure that the package is initialized, without using any of the functions or variables in the package, you can use a blank identifier if you need to ensure that the INIT function of the package is called, and you do not need to use the package in your code.
import (_ "packagename")
When importing a package using import, if a package naming conflict occurs, you can precede the name of the import with a package alias. Here's how to use it:
import (packageAnotherName "packagename")

4. init function

All packages can contain an init function. The INIT function should not have any return value types and parameters, nor can it be explicitly called in user code. The init function is in the following form:
func init() { }
The INIT function can be used to perform initialization tasks, or it can be used to verify the correctness of a program before starting execution.
The package is initialized in the following order:
A, first initialize the packages level variables
B, immediately after calling the Init function. A package can have multiple init functions (in one file or in multiple files) and are called in the order in which the compiler resolves them.
C, if a package is imported into another package, the imported package is initialized first.
D, a package can be imported multiple times, but will only be initialized once.
The main package is initialized in the following order:
A, first initialize the imported package.
B, then initialize the variable at the package level.
C. Call the init function of the main package.
D, finally call the main function.

Iii. extension of existing types

The go language uses definition aliases and combinations to extend an existing type.

1. Use combination expansion

You can extend an existing type by defining a new type, internally combining objects to extend the type. If the TreeNode type is extended, a sequential traversal method is added.

//使用组合扩展TreeNode类型type BinTreeNode struct{   node *TreeNode}//BinTreeNode的方法func (binTreeNode *BinTreeNode)postOrderTraverse(){   if binTreeNode != nil && binTreeNode.node != nil{      left := BinTreeNode{binTreeNode.node.Right}      left.postOrderTraverse()      right := BinTreeNode{binTreeNode.node.Left}      right.postOrderTraverse()      node := binTreeNode.node      node.Print()   }}
2. Using alias Extension

An alias can be defined on an existing type, and an extension of an existing type is implemented by adding a new method to the alias type.

//定义TreeNode的别名type PreOrderTreeNode TreeNode//定义PreOrderTreeNode类型的方法func (pNode *PreOrderTreeNode)preOrderTraverse(){   if pNode != nil{      node := (*TreeNode)(pNode)      node.Print()      //打印左子树      left := (*PreOrderTreeNode)(pNode.Left)      left.preOrderTraverse()      //打印右子树      right := (*PreOrderTreeNode)(pNode.Right)      right.preOrderTraverse()   }}
3. Program examples
Package Mainimport ("FMT") type TreeNode struct{value int left,right *treenode}func createtreenode (value int) *tree node{return &treenode{value:value}}func (node TreeNode) Print () {fmt. PRINTLN (node. Value, "")}func (node *treenode) traverse () {if node! = nil{//recursive traversal of left subtree node. Left.traverse () node. Print ()//recursively traverse right subtree node. Right.traverse ()}}func (node *treenode) setValue (value int) {if node!= nil{node. Value = value}else {fmt.   PRINTLN ("The node is nil.") }}//uses the combination extension TreeNode type Postodertreenode struct{node *treenode}//bintreenode method func (Bintreenode *postodertreenode ) Postordertraverse () {if bintreenode! = Nil && Bintreenode.node! = nil{Left: = Postodertreenode{bintreenod E.node.right} left.postordertraverse () Right: = Postodertreenode{bintreenode.node.left} Right.postordertrav Erse () Node: = Bintreenode.node node. Print ()}}//defines TreeNode alias type Preordertreenode treenode//definition PreordertreenoThe method of the De type func (pnode *preordertreenode) Preordertraverse () {if pnode! = nil{Node: = (*treenode) (pnode) node. Print ()//*preordertreenode Left: = (r) (Pnode.left) Left.preordertraverse ()//Print Right sub-tree: (*preordertreenode) (pnode.right) Right.preordertraverse ()}}func main () {var root TreeNode root. Value = 0 root. left = &treenode{value:1} root. right = &treenode{2,nil,nil} root. Left.left = &treenode{value:3} root.traverse () Root.setvalue (+) Root.traverse () fmt. Println () RootItem1: = Postodertreenode{&root} rootitem1.postordertraverse () fmt. Println () RootItem2: = (preordertreenode) (root) rootitem2.preordertraverse ()}
Four, go environment variable 1, goroot

The GOROOT environment variable is the go installation path.

GOROOT=/usr/local/goexport GOROOT

To execute the GO command and Go tool, you need to configure the path of the go executable file:
export $PATH:$GOROOT/bin
If Windows needs to be used; symbols are split two paths, Mac and Unix-like use: Symbolic segmentation.

2, Gopath

Go install/go get and go tools are used to gopath environment variables.
Gopath is a working space for the Go language development, as the search path for the compiled binary storage destination and import package.
Gopath represents the address where the code package resides, and can be set more than one.
The GOPATH environment variable defaults to the Go directory under the current user's home directory, and all projects and third-party libraries are placed under the same gopath.
Gopath is used to store the go source, go executable files, and the corresponding compiled package files. So there are three subdirectories under this directory: src, bin, pkg
Gopath allow multiple directories, when there are multiple directories, note the delimiter, multiple directories when Windows is a semicolon, the Linux system is a colon, when there are multiple Gopath, the default will be the "go get" content in the first directory.
$GOPATH? directory conventions have three subdirectories:
A, src directory to store source code (such as:. Go. C. h, etc.)
B, the PKG directory holds the compiled package (for example:. a)
C, Bin directory holds the executable file generated after compilation
The Gopath cannot be set to the Go installation path, you can create a directory in the user directory, such as go.

GOPATH=/home/user/go:/home/user/devexport GOPATH

For ease of use, it is often necessary to add the bin path of all workspaces to the PATH environment variable, such as:
export $PATH:$GOPATH/bin
If $gopath has multiple working directories, use the? ${gopath//://bin:}/bin to add all bin directories.
export $PATH:${GOPATH//://bin:}/bin
Gopath has two directories (one for third-party packages, one for user development), if you use the Go tool for third-party package installation, the default installs to the first directory (/HOME/USER/GO), if you write code in/home/user/dev, use the G tool (go Install,?go build) installs the binary package into the/home/user/dev.
Gopath The advantage of setting two directories is that the first directory is the location of the third-party package, and the second directory serves as the developer's own workspace. Third-party Gopath are placed first, and the Go installation tool will use it as the default location.
When searching for a package using the GO command, first search for the $GOROOT path, then the $GOPATH/SRC path.

3. Remote Package

The Go language has a tool to get a remote package that is go get, and now go get supports most open source communities (for example: GitHub, Googlecode, BitBucket, Launchpad).
go get github.com/xxx/xxx
The go get-u parameter automatically updates the package, and when go gets it automatically obtains other third-party packages that the package relies on, which is installed by default to the first directory in $gopath.
Using a remote package in your code is the same as using a local package.
import?"github.com/xxx/xxx"

Go language Development (iv), go language object-oriented

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.