Golang Base Line

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Go Structural body Details

Go is an object-oriented language

Packaging

    • Status (attributes)

    • Behavior (method)

Visibility/invisibility (uppercase/lowercase)

Re-usability

    • Inheritance (combination)

Overloading of methods

    • Polymorphic

Interface

    • Traditional no, object-oriented programming language

    • Data Structures form a class

    • You can create an object through the template of the class

    • Properties and methods are encapsulated in a class

Types in Go

Go type: base type, reference type, struct type, custom type

In the Go language, reference types have slices, dictionaries (map), interfaces, function types, and channels (Chan).

A struct type is used to describe a set of values, such as a person's height, weight, name, and age, which is essentially an aggregated type of data

The compiler for the type alias Go does not do the implicit type conversion as in Java.

package mainimport "fmt"type foo intfunc main() {    var myAge foo    myAge = 44    fmt.Printf("%T %v \n", myAge, myAge)}

Initialization of the struct body

type person struct {    first string    last  string    age   int}func main() {    p1 := person{"James", "Bond", 20}    p2 := person{"Miss", "Moneypenny", 18}    fmt.Println(p1.first, p1.last, p1.age)    fmt.Println(p2.first, p2.last, p2.age)}

Methods of struct method structure body

type person struct {    first string    last  string    age   int}func (p person) fullName() string {    return p.first + p.last}func main() {    p1 := person{"James", "Bond", 20}    p2 := person{"Miss", "Moneypenny", 18}    fmt.Println(p1.fullName())    fmt.Println(p2.fullName())}

Combination type Inline type

type person struct {    First string    Last  string    Age   int}type doubleZero struct {    person    LicenseToKill bool}func main() {    p1 := doubleZero{        person: person{            First: "James",            Last:  "Bond",            Age:   20,        },        LicenseToKill: true,    }    p2 := doubleZero{        person: person{            First: "Miss",            Last:  "MoneyPenny",            Age:   19,        },        LicenseToKill: false,    }    fmt.Println(p1.First, p1.Last, p1.Age, p1.LicenseToKill)    fmt.Println(p2.person.First, p2.Last, p2.Age, p2.LicenseToKill)

Overrides for property methods

Declares a type of struct type, if the type is nested, if the outer layer does not have the inner properties and methods can directly get the properties and methods of the inner layer
If the outer layer also declares the same familiarity and method, then overrides occur, similar to object-oriented overrides, which are nested in go as traditional object-oriented inheritance

Pointer to struct body

A pointer to a struct can change the properties and methods of the struct body.
"Go
Type person struct {
Name string
Age int
}

Func Main () {
P1: = &person{"James", 20}
Fmt. Println (p1)
Fmt. Printf ("%t\n", p1)
Fmt. Println (P1.name)
Fmt. Println (P1.age)
}

#### 结构体序列化>结构体的属性要大写,不然不能够序列化```gotype person struct {    First       string    Last        string    Age         int    notExported int}func main() {    p1 := person{"James", "Bond", 20, 007}    bs, _ := json.Marshal(p1)    fmt.Println(bs)    fmt.Printf("%T \n", bs)    fmt.Println(string(bs))}

Variable scope

Variables for packages

var x = 42func main() {    fmt.Println(x)    foo()}func foo() {    fmt.Println(x)}

Scope of package variables and exportable

In go, a variable or method named uppercase means it can be exported and can be used arbitrarily in the same package

// MyName is exported because it starts with a capital lettervar MyName = "Todd"var yourName = "Future Rock Star Programmer"

Variable in the scope of the method

func main() {    x := 42    fmt.Println(x)    foo()}func foo() {    // no access to x    // this does not compile    fmt.Println(x)}

Variable scope of Go

The variable scope of Go is determined by the curly braces, and the scope of any variable is within the curly braces in which it is located
If, for, and so on can have an initialization expression, and its scope is higher than the next curly brace layer

Closed Package

If-else

General If-else

If a==1{
Fmt. Println ("A=1")
}

If Else local variables

       if food := "Chocolate"; b {        a := true        if a {            food := "banana"            fmt.Println(food)        } else {            food := "apple"            fmt.Println(food)        }        fmt.Println(food)    }

If else else if else

   if false {        fmt.Println("first print statement")    } else if true {        fmt.Println("second print statement")    } else {        fmt.Println("third print statement")    }

Cycle

For loop

for i := 0; i <= 100; i++ {        fmt.Println(i)    }

For range

When used to iterate over arrays and slices, the range function returns indexes and elements;
When used to traverse a dictionary, the range function returns the key and value of the dictionary.

Array

Normal array

var a [23]intfmt.Println(x)    fmt.Println(len(x))    fmt.Println(x[42])    x[42] = 777    fmt.Println(x[42])

Literal array

[3]int [4]int is two completely different types

var q [3]int = [3]int{1, 2, 3}var r [3]int = [...]int{1, 2, 4}

Slice

Myslice: = []int{1, 3, 5, 7, 9, 11}

Dictionary

The difference between make and new

Interface

A destructor method without interfaces

type square struct {    side float64}func (z square) area() float64 {    return z.side * z.side}func main() {    s := square{10}    fmt.Println("Area: ", s.area())}

struct method with interface

type square struct {    side float64}func (z square) area() float64 {    return z.side * z.side}type shape interface {    area() float64}func info(z shape) {    fmt.Println(z)    fmt.Println(z.area())}func main() {    s := square{10}    fmt.Printf("%T\n",s)    info(s)}

Error handling

An error occurred without exception handling

Program Unexpected error FMT print
"Go
_, Err: = OS. Open ("No-file.txt")
If err! = Nil {
Fmt. Println ("Err happened", err)

}
#### 发生错误没有进行异常处理>程序发生异常错误 log打印```go    _, err := os.Open("no-file.txt")    if err != nil {        //        fmt.Println("err happened", err)        log.Println("err happened", err)        //        log.Fatalln(err)        //        panic(err)    }

An error occurred without exception handling

The program has an exception error log printed inside the text

func init() {    nf, err := os.Create("log.txt")    if err != nil {        fmt.Println(err)    }    log.SetOutput(nf)}func main() {    _, err := os.Open("no-file.txt")    if err != nil {        //        fmt.Println("err happened", err)        log.Println("err happened", err)        //        log.Fatalln(err)        //        panic(err)    }}

Exception handling functions

Defer represents the function that is always executed after execution to execute defer

func clean(){    fmt.Println(" do something in clean ")}func main(){    defer clean()    fmt.Println("end main")}

Defer

(basic function) Simply put, this function of defer is executed automatically after the defer function executes all the code.
"Go
Func Main () {
Defer second ()
First ()
}

Func First () {
Fmt. Println ("First")
}

Func second () {
Fmt. Println ("second")
}
First
Second

>局部函数```gofunc main() {    defer second()    defer third()    first()}func first() {    fmt.Println("first")}func second() {    fmt.Println("second")}func third() {    fmt.Println("third")}

Stack characteristics
"Go
Func Main () {
Defer second ()
Defer third ()
First ()
}

Func First () {
Fmt. Println ("First")
}

Func second () {
Fmt. Println ("second")
}

Func third () {
Fmt. Println ("third")
}

>### panic>panic相当于一个运行时异常>遇到panic的时候,会停止当前函数剩下来的语句,但在退出该函数之前,会执行defer的语句>依据函数调用层次,panic依次终止每个函数,直至main()。### recover>recover相当于try-catch的catch部分,使得panic不再传递。而defer相当于try-catch-final的final部分。```gofunc main() {    f()}func final_print(msg string) {    fmt.Println(msg)}func f() {    fmt.Println("f.1")    g()    fmt.Println("f.2")}func g() {    defer func() {          str := recover()          fmt.Println(str)    }()    defer final_print("g.defer()")    fmt.Println("g.1")    h()    fmt.Println("g.2")}func h() {    defer final_print("h.defer()")    fmt.Println("h.1")    panic("panic in h()")    fmt.Println("h.2")}

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.