Golang the most basic grammar

Source: Internet
Author: User

This section looks at the basic syntax of Golang ... Well ... If you are too lazy to see, remember the following two points is good:
1 Golang variables, function parameters and so on are related to the declaration of the type, all the variable name is written before, the type is written in the back (and the Orthodox C-system syntax just opposite)
2 Loop statement for all
And then, here we go.

Go Language Basic grammar

package mainimport (    "fmt")func main() {    fmt.Println("Hello Azen٩(●˙▿˙●)۶…⋆ฺ")}

Function: Use the FMT to run the output of this library

Defining variables

var keyword

func variableZeroValueDefine() {    var a int    var s string    fmt.Printf("%d %q\n", a, s)}

Knowledge Points:

    1. The variable name is written in front, and the variable type is written behind
      Cause: When defining a variable, it's often the first name that comes to mind, and then the variable type
    2. After the variables are defined, the variables have a default initial value.
      2.1. int type has an initial value of 0
      2.2. String type Initial empty string-use%q to print an empty string, showing the result → ""

Define variables and assign initial values at the same time

Note: After the variable definition, be sure to use, otherwise the compiler error.

func varibaleInitial() {    var a, b int = 1, 2    var s string = "猜猜我是谁"    fmt.Println(a, b, s)}

In this example, int and string are superfluous, and the compiler can do type inference-type deduction

Type inference

func varibaleTypeDeduction() {    var a, b, c, s = 1, 2, true, "ㄟ..."    b = 666    fmt.Println(a, b, c, s)}

: = defines and assigns an initial value

It is more recommended to define and initialize variables in this way

func varibaleShortcut() {    a, b := 233, 666    s := "老铁蛤蛤蛤"    fmt.Println(a, b, s)}

Defining variables outside of a function

var a, b intvar ss = "总想搞个大新闻"

Variables defined outside the function, not global variables, but in- package variables .
Go language Wood has a global variable argument.

Note: Defining a variable outside of a function is not possible by: =, must be modified by the VAR keyword

Define multiple in-package variables using ()

Variables can be defined in parentheses to reduce the number of uses of the VAR keyword

var (    s string    a, b int    // a, b := 666, 233 // 全局变量不能用:=定义)var ss = "总想搞个大新闻"

Built-in variable type

    • Bool,string
    • (u) int, (U) int8, (U) int16, (U) Int32, (U) Int64, uintptr
      • Length varies by operating system number of digits
      • UIntPtr is a pointer.
    • Character type
      • Byte
      • Rune
        • Not a Char,char, only 1 bytes.
        • The length of the rune is 32 bits, 4 bytes, to deal with the globalization of characters
    • Floating point number
      • Float32,float64
      • complex64,complex128
        • Plural, with real and imaginary parts
        • The real and imaginary parts of the complex64 are 32-bit
        • The real and imaginary parts of the complex128 are 64-bit
        • The complex number is directly used as the type of the built-in variable

Forcing type conversions

Golang only coercion type conversions, no implicit type conversions
Example: Calculating the length of the hypotenuse
A = 3 B = 4 for hypotenuse c

func triangle() {    var a, b = 3, 4    var c int    c = int(math.Sqrt(float64(a * a + b * b)))    fmt.Println(c)}

Math. The SQRT function's entry and exit parameters are float64, so casting is required.

Definition of constants

Keyword: const
Constant types may or may not be specified

    • If you do not specify a type, the constant will be the same as the text substitution function (similar to a macro definition), where it is used to determine the type

The Golang does not capitalize all the constants because the first capitalization in Golang represents the scope as public

func consts() {    const (        filename = "abc.txt"        a, b     = 3, 4    )    var c int    c = int(math.Sqrt(a * a + b * b))    fmt.Println(filename, c)}

* Note: The above a*a does not have to be forced to float64, because it is a similar "macro replacement"

Enum type

Basic definition: It's better to define a set of const

func enums() {    const (        azen  = 0        daker = 1        buran = 2    )    fmt.Println(azen, daker, buran)}

Iota Self-increment

Defining enumerations

func enums() {    const (        azen  = iota        daker        _        buran    )    fmt.Println(azen, daker, buran)}

Iota participate in the operation

const (    b = 1 << (10 * iota)    kb    mb    gb    tb    pb)

Conditional statements

If statement

func bounded(v int) int {    if v > 100 {        return 100    } else if v < 0 {        return 0    } else {        return v    }}

Features: If conditions do not need to be wrapped in parentheses
Example:

func ReadFile(filename string) ([]byte, error)

Returns a value of two:

    • []byte is the read-to-file content array-print content using%s
    • Error is a fault message
func fileRead() {    const filename = "abc.txt"    contents, err := ioutil.ReadFile(filename)    if err != nil {        fmt.Println(contents)    } else {        fmt.Println(err)    }}

To use or simplify a condition

func fileRead() {    const filename = "abc.txt"    if contents, err := ioutil.ReadFile(filename); err != nil {        fmt.Println(contents)    } else {        fmt.Println(err)    }}

In a condition you can use: = Make declarations and assign values
If the scope of the if is not accessible as defined on the content and err

Switch statement

Basic usage

func eval(a, b int, op string) int {    var result int    switch op {    case "+":        result = a + b    case "-":        result = a - b    case "*":        result = a * b    case "/":        result = a / b    default:        panic("不支持的操作类型")    }    return result}

Characteristics:

    • There is no need to add a break and the default is break.
    • If you do not need a break, manually add Fallthrough-this is the same as Swift

Panic

Throws an error-similar to Nserror's raise

switch is not followed by an expression

Add a condition to the case

func grade(score int) string {    var g string    switch {    case score < 0 || score > 100:        panic(fmt.Sprintf("Wrong score: %d", score))    case score < 60:        g = "F"    case score < 80:        g = "B"    case score < 90:        g = "A"    case score <= 100:        g = "SSR"    }    return g}

Looping statements

For statement

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

Chestnuts: Turn binary

The idea of turning binary: constantly take the mold, get the number forward plus

func convertToBin(number int) string {    result := ""    for ; number > 0; number /= 2 {        lsb := number % 2        result = strconv.Itoa(lsb) + result    }    return result}

StrConv. itoa→ int to string

For while usage (only end condition)

func pintFile(filename string) {    file, err := os.Open(filename)    if err != nil {        panic(err)    }     scanner := bufio.NewScanner(file)    //  func (s *Scanner) Scan() bool - 在读完或报错的时候,会返回false    for scanner.Scan() {             }}

When the For statement, omit the fact condition, increment condition, only when the end condition, similar to while

For omitting all expressions-dead loops

func forever() {    for {        fmt.Println("Bilibili")    }}

Golang often use the cycle of death, Goroutine Belly is a cycle of death. A lot of dead loops of goroutine are communicating with each other. -This is the same as the Runloop in iOS development

function definition

Func eval (A, B int, op string) int

The function name is before, and the type is behind. Consistent with variable definition ideas

Basic example

func convertToBin(number int) string {    result := ""    for ; number > 0; number /= 2 {        lsb := number % 2        result = strconv.Itoa(lsb) + result    }    return result}

function returns an example of multiple values

with remainder division

func div(a, b int) (int, int) {    return a / b, a % b}

Name the return value

The benefit is more readable, and the function caller can easily know what the return value is ...

func div(a, b int) (q, r int) {    return a / b, a % b}

Q and R can also be returned correctly, but the readability is not strong, it is not recommended to write

func divNoRecommend(a, b int) (q, r int) {    q = a / b    r = a % b    return}

Multiple return values use only one

result, _ := div(10, 7)

Customary usage of multivalued returns

The first value returns the normal value, and the second returns an error

Functional and functional programming

The function is a class citizen in Golang, and the function can be used as a parameter, return value

function as a parameter

func apply(op func(a, b int) int, a, b int) (result int)  {    return op(a, b)}

Print the OP and see who it is.

    • The name of the letter of hold
      • Need to use reflect. ValueOf (OP). Pointer () Get the pointer to this function
      • Use runtime to get the function name runtime. FUNCFORPC (P). Name ()
func apply(op func(a, b int) int, a, b int) (result int)  {    p := reflect.ValueOf(op).Pointer()    opName := runtime.FuncForPC(p).Name()    fmt.Println(opName)    return op(a, b)}

Anonymous functions as function arguments

fmt.Println(    apply(func (a, b int) int {        return a + b    }, 10, 20),)

Golang No fancy lambda expression

Additional description of the function

Variable parameter list

The use of a mutable parameter list can be used in the same way as an array

func sum(numbers ...int) int {    result := 0    for i := range numbers {        result += numbers[i]    }    return result}

No default parameters, optional parameter concept

Pointer

func pointerDefine() {    var a = 0    var pa *int = &a    *pa = 0x66CCFF    fmt.Println(a)}

Characteristics

    • Pointers cannot be calculated
      • C can get the pointer to the head pointer to do the addition operation-the step is determined by the pointer type

function parameter passing

C, C + +, OC can be value-transmitted, can also refer to the
Java and Python are basically reference passing

Golang only values are passed one way

Where the function is adjusted, the parameters are copied one copy-and the pointer mates to achieve the effect of a fairly quoted pass

Example: Exchanging values for two variables

func swap(a, b *int) {    *a, *b = *b, *a}

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.