Golang Basic Grammar (1)

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

Golang Basic Grammar (1)

Declaration of a variable

In the go package, a variable or method function or constant starts with a capital letter and can be seen outside of the package.
Either a package variable or a package method or a package constant that can be exported
Lowercase package variables and package methods There are package constants that can only be accessed within the package

    • The following definition methods can be used both in and out of the function body

//定义一个变量,名称为 "numberOfTimes",类型为 "int"var numberOfTimes int//定义三个变量,类型为 “int"var var1, var2, var3 int//定义一个变量,名称为 "numberOfTimes",类型为 "int",值为 "3"var numberOfTimes int = 3//定义三个类型为 "int" 的变量,并且初始化它们的值var var1, var2, var3 int = 1, 2, 3
    • Variable declaration shortcut (only within a function or method)

package main//var foo string//foo := "test"func main(){    var bar int    foo1 := 10    //v1 v2 v3可以是任意类型,编译器会自动确认数据类型    vname1, vname2, vname3 := v1, v2, v3        //下面的 var1 := 11会报错,因为变量 var1已经被定义,不能重复定义    var var1 int = 10    var1 := 11    //下面正确,只是给 var2重新赋值    var var2 int = 10    var2 = 12}
    • Special variables (deprecated variables or imported packages not used)

A package or variable that is not used in the Go language can cause compilation to fail

//"net/http" 包导入不使用,如果包里面有 init 方法,只执行 init 方法import(    "fmt"    _ "net/http")func main(){    //函数 divede 返回值第一个放弃不使用    _, remainder := divide(10, 3)}
    • Grouping definitions

//导入包import(    "fmt"    "os")//常量定义const(    i = 100    pi = 3.1415    prefix = "Go_")//变量var(    i int    pi float32    prefx string)//结构体type(    people struct{        name string        age int    }    animal struct{        name string        leg int    })
    • Keyword Iota

const(    x = iota // x == 0    y = iota // y == 1    z = iota // z == 2    w // 省略 iota ,w == 3)const(    a = iota // a == 0    b = 10    c // c == 1    d // d == 2)const v = iota //v ==0const(    e, f, g = iota, iota, iota // e==0, f==0, g==0 因为在同一行)

Attributes of the base data type

  • Boolean type

    • BOOL denotes Boolean type

    • BOOL has a value of true and False and the default value is False

    • The value of bool cannot be converted to a number

  • Numeric type

    • Reshape int

      • Shaping is divided into signed int and unsigned uint, which have the same length, depending on the operating system, 32-bit OS 32-bit, 64-bit operation System for the

      • Go language also defined Rune,byte,int (8,16,32,64), uint (8,16,32,64)

      • Rune is the alias of Int32, Byte is U int8 alias

      • Go language does not allow different integer assignments

       var a int8 = 10var b int32 = 10//compile error C: = A+b  
    • Float type

      • Only float32 and float64, no float

    • plural complex

  • Strings string

    • Go using UTF-8 encoding

    • "" or "wrapped up is a string

    • String does not allow changing values

    • Ways to change a string

    s := "hello"c := []byte(s)c[0] = 'c's2 := string(c)//思考下面的代码 s1的地址是固定不变的还是会变?//s1 的地址不会改变,string 底层是一个结构体,两个字段//其中一个是指向数据的指针//另外一个是数据的长度s1 := "hello"s1 = "sea"s1 = "aa" + s1[1:]
    • Connect two strings using "+"

    • ' Multiline string, without escaping any characters

    m := `helloworld`

Wrong type error types

Go has no exception handling mechanism, built-in error type, for handling errors
Go requires that we either explicitly handle an error or ignore

Array, slice, map

    • Array definition

var arr [n]typea := [3]int{1, 2, 3}//... 自动识别数组长度a := [...]int{1,3,3}d := [2][2]int{[2]int{0,0}, [2]int{2,2}}d1 := [2][2]int{{1,1}, {22,22}}
    • Slice definition

var fslice []intslice := []byte{'a', 'c', 'd'}
    • Slice operation

a := []int{1,2,3,5}b := a[1:] // b 为 2,3,5 但是 a  b 共享底层数据结构,修改 a 或者 b , a和 b 都会改变b := a[:2] // b 为 1, 2
    • Built-in functions

      • Len gets slice length

      • Cap gets slice maximum capacity

      • Append appends one or more elements to slice, returning slice

      • Copy copies one slice to another, returning the number of elements in copy

    • Map-Similar to the dictionary inside Ptyon key-value

      • Map is not ordered, each printout is not the same order, use key to get value

      • Map has no fixed length, as is the reference type as slice

      • The Len function can be used on a map to return how many keys the map now contains

      • Map can easily modify value by key

      • Delete to remove the element from the specified key in the map

The index of the slice can only be the int,map of any type you want

numbers := make(map[string]int)numbers["one"] = 1

Make New difference

    • Make allocates memory to built-in types and initializes them, returning non-0 values

      • Map

      • Slice

      • Channel

    • New (T) returns a value of 0

Control structures and functions

    • If no parentheses are required

if test {}//分号隔开,赋值if x := len(slice); x >0 {}
    • Goto

func my(){    i := 0Here:   //label goto    i++    goto Here //跳转到 Here}
    • For alternative to While,do-while

      • Break continue

    • Switch

      • The value of case can be separated by multiple commas

      • Do not need break for matching case only

      • Default if there is no matching execution

    • Func definition function

      • The function has 0-more arguments, the parameter name is before the parameter type

      • Functions can return multiple values or do not return a value

      • Changeable parameters ...

      • The go function parameter is essentially a pass value

      • Functions can be treated as values and parameter types

func funcName(p1 type1, p2 type2)(returnType1, returnType2{    return a, b}func varFunc(arg1 ...int){}
    • Defer deferred execution, advanced back out FILO

    • Panic & Recover

    • Main & init functions

      • The main function of the main package is the program entry

      • Each package can have more than one init function, executed at IMPPRT, for some initialization, and each file in the package can only have one init function.

    • Import Imports Package

      • . operator, or you can ignore the name of the call

      • Alias

      • _ Import only does not use

import(    . ”fmt" //忽略包名    o "os"  //别名    _ "net/http"    //导入包执行 init 方法不使用)

Not to be continued

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.