Go基本语法

Golang学习

Hello World

1
2
3
4
5
6
7
package main

import "fmt"

func main() {
fmt.Println("Hello World")
}

Variables assignment

1
2
var age int
age = 20
1
2
// recommanded
age := 20
1
2
// unpack, like python.
name, age := "Bob", 20

Constants define

1
const Distance = 1000

Basic types

  • strings

    1
    2
    3
    s0 := "string"
    s1 := `mutiple
    strings`
  • numbers

    1
    2
    3
    i := 100  //int
    f := 1.0 //float64
    b := byte('a') //byte
  • array

    1
    2
    3
    // The size of array is fixed.
    arr := [5]string{"a", "b", "c", "d", "e"}
    arrAuto := [...]int{1, 2, 3, 4, 5, 6}
  • slice

    1
    2
    // slice has a dynamic size, unlike array.
    slice := []int{9, 10, 100, 73}
  • map

    1
    2
    3
    // type of key is string
    // type of value is nil slice
    dict := map[string][]string{}

Flow control

  • conditional

    1
    2
    3
    4
    5
    6
    7
    if myAppearance == "handsome" && myMoney == "countless" {
    doAnythingIWanna()
    }else if myMoney == "good" {
    sleepAndEatAnytime()
    }else {
    code()
    }
  • statement in if

    1
    2
    3
    if res, err := getResult(); err != nil {
    doRightThing()
    }
  • switch

    1
    2
    3
    4
    5
    6
    7
    8
    switch sex {
    case "male":
    fmt.Println("hi, man")
    case "female":
    fmt.Println("hi, women")
    default:
    fmt.Println("excuse me, who are you?")
    }
  • for range loop

    1
    2
    3
    4
    slice := []string{"h", "e", "l", "l", "o"}
    for index, item := range slice {
    fmt.Printf("%d====>>%s", index, item)
    }
  • for loop

    1
    2
    3
    for i := 0; i <= 10; i++ {
    fmt.Println(i)
    }

Function

1
2
3
func sum(x, y int) int {
return x + y
}
1
2
3
4
func flow(file *fileType) {
// outside variable will be changed
change(file)
}

©Written By flyaooo