Golang Study Notes (1)--Basics

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

This article is reproduced, original: Golang study notes (1)--Basic

Golang Introduction

The go language is an open source project developed by Google, one of the aims to improve developer productivity. Go language grammar is flexible, concise, clear and efficient. Its concurrency features can be easily used for multicore processors and network development, while flexible and novel type systems can easily be written in a modular system. Go can be compiled quickly, with the garbage Memory auto-recycle feature, and also support runtime reflection. Go is an efficient, static type, but has a system-level syntax that interprets the dynamic type characteristics of a language.

Language Basics

First GO Program

We learn every language without a hello world beginning. Now we're going to present our first program.

package mainimport "fmt"func main(){    fmt.Println("hello world")}

The result of the operation is as we expected:



Code explanation

The first line, which package defines the package main . The second line, introduces the fmt package, func main() defines the main function, is the func keyword that defines the function, and in the main function calls the fmt Println method output string in the package hello world .

注意

    1. In the go language, the semicolon at the end of a statement ; can be omitted
    2. In the go language, the initial curly brace of the snippet { cannot be wrapped, or the program will error.

Basic type

type Length (bytes) Description
bool 1 true, false . Cannot treat a value other than 0 as true
Byte 1 Uint8 aliases
Rune 4 Int32 aliases. Represents a Unicode character
Int/uint 4 Depending on the platform you are running, it may be 32bit or 64bit.
Int8/uint8 1 1-128 ~ 127; 0 ~ 255
Int16/uint16 2 -32768 ~ 32767; 0 ~ 65535
Int32/uint32 4 -2.1 billion ~ 2.1 billion; 0 ~ 4.2 billion
Complex64 8 Plural type, i.e. 32-bit real number + 32-bit imaginary number
complex128 16 plural type, i.e. 64-bit real number + 64-bit imaginary number
UIntPtr A 32-bit or 64-bit integer that can hold the pointer
Array Array, value type, such as: [2]int
struct struct, value type
String Value type
Slice Reference types, such as: []int
Map Reference type
Channel Reference type
Interface Interface type
function function type

Defining variables

package mainimport "fmt"func main(){    var b bool //定义指定类型的变量    var n int  //定义指定类型的变量    var i int = 3 //定义指定类型的变量,并赋予默认值    var(          //多变量的定义        aa int  = 4        str string    )    var i1,i2,i3 int = 1,2,3 //多个同类型的变量定义,并赋值    var strName = "bob"  //go会自动检测变量的类型    strSex := "male"    //:=定义变量,并给变量赋值,可省略var关键字    fmt.Println("n = ", n)    fmt.Println("i = ", i)    fmt.Println("b = ", b)    fmt.Println("aa = ", aa)    fmt.Println("str = ", str)    fmt.Println("i1 = ", i1, "i2 = ", i2, "i3 = ", i3)    fmt.Println("strName = ", strName)    fmt.Println("strSex = ", strSex)}

Compile run:



You will find that b=false, n=0, str=; For unassigned variables, go is automatically initialized, the value type is 0, the Boolean type is False, and the string type is empty.

Attention:
The unused variables are defined in the go Language, and the compilation will error, and the introduction of unused package compilation will also cause errors.

Constant

Constants must be defined by the compilation period, the definition of constants used const , the types of constants can be char , string bool and 数字常量 . Because of the limitations of the compiler state, the expression that defines them must be constant expressions, which can be evaluated by the compiler. For example, 1<<3 a constant expression is math.Sin(math.Pi/4) not, because math.Sin the function call occurs in the run state.

The definition of a constant is similar to a variable, except that the keyword becomes const :

const PI = 3.1415926535const msg = "hello"const(    z = false    a = 123)const x, y = "xxxx", "yyyy"

There are no enum types in the Go language and can be simulated with constants. Can be used to iota generate an automatically growing enumeration value starting from 0. Increments by row, you can omit the keywords for subsequent rows iota .

const(    Sunday = iota      //0    Monday             //1    TuesDay            //2)

can also use multiple on the same line iota , they each grow

const(    U, V = iota, iota  //U=0,V=0    W, X               //W=1,X=1    Y, Z               //Y=2,Z=2)

If a row does not want to increment, you can provide the initial value separately. However, to restore the increment, you must useiota

const(    A1 = iota //0    A2        //1    str = "hello"  //hello    s              //没有赋值,跟上一行一样    A3 = iota  //恢复递增,值为4    A4         //5)

Process Control

If Else

The If of Go is similar to that in C and Java, except that there are no parentheses

func main(){    a := 2    if a==2{        fmt.Println("a=2")    }}

You can include some initial expressions between if and conditions, and the above code can be written as:

func main(){    if a := 2; a==2{        fmt.Println("a=2")    }}

Remember, however, that there can be only one initialization expression between if and the condition, otherwise the error will be compiled.

Switch

The switch of Go is very flexible, the expression does not have to be a constant or an integer, the process is executed from top to bottom until a match is found, and if switch has no expression, he matches true.
Go inside the switch default equivalent to each case last break , the match will not automatically go down after the other case, but instead of the entire switch, but can be used to fallthrough enforce the following case code, fallthrough equivalent to remove the default after case break.

func main(){    i := 5    switch i{        case 1:            fmt.Println("i is equal to 1")        case 2:            fmt.Println("i is equal to 2")        case 3,4,5,6:            fmt.Println("i is equal to 3,4,5 or 6")        default:            fmt.Println("others")    }}

The results are as follows:



If you add the following last case fallthrough
func main(){    i := 5    switch i{        case 1:            fmt.Println("i is equal to 1")        case 2:            fmt.Println("i is equal to 2")        case 3,4,5,6:            fmt.Println("i is equal to 3,4,5 or 6")            fallthrough        default:            fmt.Println("others")    }}

As a result, the code inside the Defaul is still executed:



If you do not specify a switch condition expression, or if it is true directly, you can override the if...else if...else...Such as:
func main(){    i := 5    switch {        case i < 0:            fmt.Println("小于零")        case i > 0:            fmt.Println("大于零")        default:            fmt.Println("等于零")    }}

Results:



For

Go has only one keyword for introducing loops. However, it provides a do-while looping method that is available in addition to the C language.
There are three types of go for loops:

for init; condition; post{} //和C的for一样for condition{}             //和while一样for{}                       //死循环

Such as:

func main(){    str := "Chain"    for i, j := 0, len(str); i < j; i++{        fmt.Println(string(str[i]))    }}

Operation Result:



Use breakYou can terminate the current loop prematurely, and when you nest loops, you can breakThe following specifies the ability to label, which terminates the specified loop, such as:
func main(){    oute:        for i := 0; i < 5; i ++{            for j := 0; j < 3; j++{                if(i > 2){                    break oute                }                fmt.Println("i=",i,"j=", j)            }        }}

Results:



continueUsed to terminate the execution of the loop body, continue to the next loop, and breckSimilarly, for nested loops, you can use labels to specify which layer of loops to continue.
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.