Go language
- File entry main
- The left parenthesis must go together
- Each file must first declare the package (there must be a main package)
- No semicolon
- The guide bag must be used
data type
Declaration of variables = = > var a int
C: = 10 automatic derivation type
Multiple assignment A, B: = 10, 20 swap a, B: = B, a
Anonymous variable, b, _ = func() is used with the return value of the function
var (
a int = 1
b float64 = 1.0
)
**Constant**
const a int = 10 const a = 10
const (
a = 1
b = 1.1
)
iota enumeration constant automatic generator, but it will become 0 when encountering const
package main import "fmt" func main() { const ( a = iota b = iota c = iota ) fmt.Printf("a = %d, b = %d, c = %d", a, b, c) const d = iota fmt.Printf("d = %d", d) const ( i = iota j, k = iota, iota // Same row value h = iota ) fmt.Printf("i = %d, j = %d, h = %d", i, j, h) }
switch
package main import "fmt" func main() { fmt.Println("Please count in:") var a int fmt.Scan(&a) switch a := 1;a { case 1: fmt.Println("111") fallthrough //Jump out without default case 2: fmt.Println("222") fallthrough case 3: fmt.Println("333") default fmt.Println("444") } } switch { case a > 10: fmt.Println("111") fallthrough //Jump out without default case a < 10: fmt.Println("222") fallthrough case a == 10: fmt.Println("333") default fmt.Println("444") }
loop
package main import "fmt" func main() { sum := 0 for i := 1; i <= 100; i++ { sum = sum + i } fmt.Println("sum = ", sum) } package main import "fmt" func main() { str := "abc" for i, data := range str { fmt.Printf("str[%d] = %c\n", i, data) } for i := range str { fmt.Printf("str[%d] = %c\n", i, str[i]) } }
Jump
goto Cannot cross function package main import "fmt" func main() { fmt.Println("111111") goto End fmt.Println("222") End: fmt.Println("333333") }
function
package main import "fmt" // No parameter, no return value func MyFunc() { a := 666 fmt.Println("a = ", a) } // Return value with or without parameters func MyFunc01(a int) { fmt.Println("a = ", a) } // The indefinite parameter type must be placed last func MyFunc02(a int, args ...int) { fmt.Println("len", len(args)) MyFunc03(args[1:]...) } func MyFunc03(args ...int) { for _, data := range args { fmt.Println(data) } } // There is a return value func MyFunc04() (result int) { result = 777 return } func MyFunc05() (a int, b int, c int) { a, b, c = 11, 22, 33 return } func main() { a, b, c := MyFunc05() fmt.Println("c = ", a, b, c) }
There are parameters and return values
Recursive function
pakeage main import "fmt" func test01() (sum int) { if (i == 1) { return 1 } return i + test01(i - 1) } func main() { var sum int sum = test01(100) fmt.Println("sun = ", sum) }
Function type
pakeage main import "fmt" func add(a, b, int) int { return a + b } func bdd(a, b, int) int { return a - b } type FuncType func(int, int) int func main() { var ftest FuncType ftest = add result := ftest(10, 20) }
Callback function (function parameter has function type) (polymorphic)
pakeage main import "fmt" // Implement addition func add(a, b, int) int { return a + b } // Implement subtraction func bdd(a, b, int) int { return a - b } type FuncType func(int, int) int func calc(a, b, int, ftest FuncType) (result int) { Println("calc") result = ftest(a, b) return } func main() { a := calc(1, 1, add) fmt.Println("a = ", a) b := calc(1, 1, bdd) fmt.Println("b = ", b) }
Closure (anonymous function)
func main() { a := 10 str := "mike" f1 := func() { fmt.Println("a = ", a) fmt.Printlb("str =", str) } f1() type FuncType func() var f2 func() f2 = f1 func () { fmt.Println("111") } () func (i, j int) (max int) { if i > j { max = i } return } (10, 20) }
The closure reference method captures external variables (the closure is its own independent space, and the internal variables will not be released)
Defer deferred call
func main() { defer fmt.Println("bbbb") fmt.Println("aaaaaa") }
The call order (last in first out) function will also be executed if there is an error
Use with closures
func main() { a := 10 b := 20 defer func(a, b, int) { fmt.Printf("a = %d, b = %d\n", a, b) }(a, b) //It's already passed on a = 111 b = 222 fmt.Println("a ,b", a, b) }
Get named row parameters
package main import "fmt" import "os" func main() { list := os.Args n := len(list) fmt.Println("n = ", n) }
engineering management
src source file, gopath, Gobin settings
package main import print "fmt" //Must use import _ "os" //Ignore the need to use the init function func main() { n := 6 print.Println("n = ", n) }
The init function is executed before the package
// To execute the init function import ( _ "fmt" )
Composite type
Pointer
package main import "fmt" func main() { var a int = 10 var p *int = &a fmt.Println("%v", p) } --------------------- package main import "fmt" func swap(p1, p2 *int) { *p1, *p2 = *p2, *p1 } func main() { a, b := 10, 20 swap(&a, &b) fmt.Println("a b", a, b) }
new function auto recycle
package main import "fmt" func main() { var p *int p = new(int) *p = 666 fmt.Println("p = ", *p) }
array
package main import "fmt" func main() { var id [50]int //The number of elements is constant c := [5]int{1,2,3} b := [5]int{2:10, 4:20} // Comparison (= = OR! =) and assignment fmt.Println("a b", id[0], id[1]) } ----------- //random number package main import "fmt" import "math/rand" import "time" func main() { rand.Seed(time.Now().UnixNano()) for i := 0; i < 5; i++ { fmt.Println("rand = ", rand.Intn(100)) } }
Slice (dynamic array)
slice
package main import "fmt" func main() { a := []int{1, 2, 3, 0, 0} s := a[1:3:5] fmt.Println("s=", s) fmt.Println("s=", len(s)) fmt.Println("s=", cap(s)) } -------------- // Different from arrays, the capacity and length are not fixed, and the sliced data will change the original data package main import "fmt" func main() { s := []int{} // s2 := make([]int, 5, 10) // S3: = make ([] int, 5) length is the same as capacity, 5 fmt.Println("len(s),cap(s)", len(s), cap(s)) s = append(s, 11) fmt.Println("len(s),cap(s)", len(s), cap(s)) } --------------- // Slicing operation package main import "fmt" func main() { array := []int{0, 1, 2, 3} s1 := array[:] data := array[1] s2 := array[2:3:4] s3 := array[:4] s3 := array[2:] // copy } ------------ //Reference passing
map
package main import "fmt" func main() { var m1 map[int]string m2 := make(map[int]string, 10) m2[1] = "make" for key,value := m1 { } delete(m2, 1) test(m1) //Reference passing }
structural morphology
Functions using other packages, structures, and Initials must be capitalized
Lower case if any
package main import "fmt" type Student struct { id int name string sex byte age int addr string } func main() { // Sequential initialization must be complete var s1 Student = Student{1, "make", 'm', 18, "bj"} fmt.Println("s1 = ", s1) s2 := Student{name: "make"} s2.name = "mike" p2 := &Student{name: "mike"} fmt.Println("p2 = ", *p2) p2.name = "mike" // No - > }
object-oriented programming
inherit
Anonymous field
package main import "fmt" type Student struct { name string age int } type People struct { foot int head int name string //Duplicate of the same name Student *Student // Initialize multi add& } func main() { var p1 People = People{2, 1, Student{"mike", 10}} fmt.Println("p1.name", p1.name, p1.age) p1.Student.name = "mike" p2 := People{Student: Student{name: "mike"}} fmt.Println("p1.name", p2) } ------------------------- // inherit package main import "fmt" type Person struct { name string sex byte age int } func (tmp *Person) PrintInfo() { fmt.Println("tmp = ", *tmp) } type Student struct { Person id int addr string } func (tmp *Student) PrintInfo() { fmt.Println("tmp = ", *tmp) } func main() { s := Student{Person{"mike", 'm', 18}, 1, "bj"} s.PrintInfo() sfunc := s.PrintInfo //Method value sfunc() f := (*person).PrintInfo() f(&s) }
encapsulation
method
package main import "fmt" func Add(a, b int) int { return a + b } type long int // tmp is the receiver. The receiver itself cannot be a pointer. Different function names can be the same func (tmp long) Add01(other long) long { return tmp + other } type long32 long func (tmp long32) Add01(other long) long { return tmp + other } func main() { var result int result = Add(1, 1) fmt.Println("result = ", result) var a long = 2 // The receiver is the object r := a.Add01(3) fmt.Println("result = ", r) } ------------------------ package main import "fmt" type Person struct { name string sex byte age int } func (tmp Person) testprint() { fmt.Println("tmp = ", tmp) } func (p *Person) setinfo(n string, s byte, a int) { p.name = n p.sex = s p.age = a } func main() { p := Person{"mike", 'm', 18} p.testprint() var p2 Person //object (&p2).setinfo("yoyo", 'f', 22) // Reference passing p2.testprint() } ---------------- // Method set of pointer variables func main() { p := &Person{"mike", 'm', 18} p.setinfo("yoyo", 'f', 22) //Internal automatic conversion (*p).set("yoyo", 'f', 22) p2.testprint() }
Interface
Define interface
package main import "fmt" //Define interface type type Humaner interface { sayhi() } type Student struct { name string id int } func (tmp *Student) sayhi() { fmt.Println("student") } type Teacher struct { addr string group string } func (tmp *Teacher) sayhi() { fmt.Println("teacher") } func WhoSayhi(i Humaner) { i.sayhi() } func main() { /*var i Humaner s := &Student{"mike", 19} i = s i.sayhi() t := &Teacher{"mike", "go"} i = t t.sayhi() */ s := &Student{"mike", 19} t := &Teacher{"mike", "go"} WhoSayhi(s) WhoSayhi(t) } ---------------- //Interface inheritance package main import "fmt" //Define interface type type Humaner interface { sayhi() } type Personer interface { Humaner sing(lrc string) } type Student struct { name string id int } func (tmp *Student) sayhi() { fmt.Println("student") } func (tmp *Student) sing(lrc string) { fmt.Println("student", lrc) } func main() { var i Personer s := &Student{"mike", 55} i = s i.sayhi() i.sing("111") //The interface transformation parent class can receive subclasses var ipro Personer ipro = &Student{"mike", 77} var base Humaner base = ipro base.sayhi() } --------------------------- // Empty interface package main import "fmt" type Student struct { name string id int } func main() { //Universal type void* //var i1 interface{} = 1 //fmt.Println("i = ", i1) //Type Asserts i := make([]interface{}, 3) i[0] = 1 i[1] = "go" i[2] = Student{"mike", 666} for _, data := range i { if _, ok := data.(int); ok == true { fmt.Println("int") } else if _, ok := data.(string); ok == true { fmt.Println("string") } else { fmt.Println("struct") } } }
exception handling
Often used to return errors
package main import "fmt" import "errors" func MyDiv(a, b int) (result int, err error) { err = nil if b == 0 { err = errors.New("Denominator cannot be zero") } else { result = a / b } return } func main() { //err1 := fmt.Errorf("%s", "thisis normol err1") //fmt.Println("err1 = ", err1) //err2 := errors.New("this is normal err2") //fmt.Println("err2", err2) result, err := MyDiv(10, 0) if err != nil { fmt.Println("err = ", err) } else { fmt.Println("result =", result) } } -------------------- // Fatal error package main import "fmt" func testa() { fmt.Println("aaaaaaaa") } func testb(x int) { defer func() { if err := recover(); err != nil { fmt.Println(err) } }() var a [10]int a[x] = 111 //Called by default //panic("this is a panic test") } func testc() { fmt.Println("ccccccccccc") } func main() { testa() testb(20) testc() }
String operation
package main import ( "fmt" "strings" ) func main() { // Does "hello" have "hello"“ fmt.Println(strings.Contains("hellogo", "hello")) // Join combination s := []string{"abc", "hello", "mike"} buf := strings.Join(s, "x") fmt.Println("buf = ", buf) // index fmt.Println(strings.Index("abc", "cd")) buf = strings.Repeat("go", 3) fmt.Println("buf = ", buf) // Split buf = "hello@go@mike" s2 := strings.Split(buf, "@") //trim strings.Trim(" are y ok ", " ") //Fields s3 := strings.Fields(" are y ok ") } ---------------------- //String conversion package main import ( "fmt" "strconv" ) func main() { slice := make([]byte, 0, 1024) slice = strconv.AppendBool(slice, true) slice = strconv.AppendInt(slice, 123, 10) slice = strconv.AppendQuote(slice, "abc") fmt.Println("slice = ", string(slice)) var str string str = strconv.FormatBool(false) str = strconv.FormatFloat(3.14, 'f', -1, 64) fmt.Println("str = ", str) str = strconv.Itoa(6666) fmt.Println("str = ", str) a, _ := strconv.Atoi("56654") }
regular expression
package main import ( "fmt" "regexp" ) func main() { buf := "abc azc a7c aac 888"; // Interpretation rules reg1 := regexp.MustComplile(`a.c`)//a[0-9]c if reg1 == nil { fmt.Println("err") return } // Extract information result := reg1.FindAllStringSubmatch(buf, -1)// -1 means all fmt.Println("result = ", result) } --------------------- package main import ( "fmt" "regexp" ) func main() { buf := "3.14 567 asd 1.23 7. 8.99 llk1 6.66" reg := regexp.MustCompile('\d+\.\d+') if ret == nil { fmt.Println("err") return } //result := reg.FindAllString(buf, -1) result := reg.FindAllStringSubmatch(buf, -1)//grouping fmt.Println("result =", result) } ------------------------ // Reptile package main import ( "fmt" "regexp" ) func main() { buf := `document info` //Native string reg := regexp.MustCompile('<div>(?s:(.*?))</div>') if ret == nil { fmt.Println("err") return } //result := reg.FindAllString(buf, -1) result := reg.FindAllStringSubmatch(buf, -1)//grouping fmt.Println("result =", result) // filter for _, text := range result { fmt.Println("text[0] = ", text[0]) fmt.Println("text[1] = ", text[1]) } }
json
Encoding and decoding
package main import ( "fmt" "encoding/json" ) //Member variable names must be uppercase type IT struct { Company string Subject []string IsOk bool Price float64 } /* Secondary coding type IT struct { Company string `json:"-"` Subject []string `json:"subjects"` IsOk bool `json:",string"` Price float64 } */ func main() { s := IT{"IT", []string{"go", "c", "c++"}, true, 666.666} //buf, err := json.Marshal(s) //Format encoding buf, err := json.MarshalIndent(s, "", " ") if err != nil { fmt.Println("err = ", err) return } fmt.Println("buf = ", string(buf)) //analysis jsonBuf := `json character string` var tmp IT // Second parameter address passing err := json.Unmarshal([]byte(jsonBuf), &tmp) if err != nil { fmt.Println("err = ", err) return } fmt.Println("tmp = ", tmp) type IT1 struct { Subject []string `json:"subjects"` } var Tmp2 IT1 // Second parameter address passing err := json.Unmarshal([]byte(jsonBuf), &tmp2) if err != nil { fmt.Println("err = ", err) return } } ------------------ //Generate json from map package main import ( "fmt" "encoding/json" ) func main() { // Create a map m := make(map[string]interface{}, 4) m["company"] = "itcast" m["subjects"] = []string{"go", "c++"} m["isok"] = true m["price"] = 666.666 result, err := json.Marshal(m) if err != nil { fmt.Println("err = ", err) return } fmt.Println("result = ", string(result)) jsonBuf := `json character string` m := make(map[string]interface{}, 4) // Second parameter address passing err := json.Unmarshal([]byte(jsonBuf), &m) if err != nil { fmt.Println("err = ", err) return } fmt.Println("m = ", m) // Cannot be assigned directly //var str string //str = m['conmpany'] // Need to push back var str string for key, value := range m { switch data := value.(type) { case string: str = data case bool: case float64: } } }
File operation
package main import ( "fmt" "OS" "io" "bufio" ) func WriteFile(path string) { //Open file f, err := os.Create(path) if err != nil { return } //close defer f.close() var buf string for i := 0 i <10; i++ { buf = fmt.Sprintf("i = $d\n", i) f.WriteString(buf) } } func ReadFile(path string) { f, err := os.Open(path) if err != nil { return } defer f,close r := bufio.NewReader(f) //Read one line r.ReadBytes('\n') } // Read one line at a time func ReadFileLine(path string) { f, err := os.Open(path) if err != nil { return } defer f,close buf := make([]byte, 1024 * 2) n, err := Read(buf) if err != nil && err != io.EOF { //ending return } fmt.Println("buf = ", string(buf[:n])) } func main() { //os.Stdout.Close() //os.Stdout.WriteString("are y ok") path = "./demo.txt" WriteFile(path) ReadFile(path) }
Copy file case
package main import ( "fmt" "OS" "io" ) func main() { list := os.Args if len(list) != 3 { fmt.Println("err") return } srcFileName := list[1] dstFileName := list[2] if srcFileName == dstFileName { fmt.Println("err") return } sf, err1 := os.Open(srcFileName) if err1 != nil { fmt.Println("err") return } df, err 2 := os.Open(dstFileName) if err2 != nil { fmt.Println("err") return } defer sf.Close() defer df.Close() buf := make([]byte, 4 * 1024) for { n, err := sf.Read(buf) if err != nil { if err == io.EOF { break } fmt.Println("err") } df.Write(buf[:n]) } }
go advantage
Concurrency (alternate use of time slice rotation) and parallelism
Concurrency at the voice level supports GC automatic garbage collection and synchronization through communication
goroutine
go collaboration. There are more than a dozen goroutines. The underlying layer may be 5 or 6 threads. go voice realizes the shared memory between goroutines
package main import ( "fmt" "time" ) func newTask() { for { fmt.Println("this is new") time.Sleep(time.Second) } } // The main process exits and the sub process exits func main() { go newTask() //Create a new collaboration for { fmt.Println("this is main") time.Sleep(time.Second) } } ---------------------- // runtime package setup coroutine package main import ( "fmt" "runtime" ) func main() { go func() { for i:= 0; i <5; i++ { // Terminate the process, and all the procedures in the process are over runtime.Goexit() // Set the number of CPUs n := runtime.GOMAXPEOCS(2) fmt.Println("go") } } () for i:= 0; i < 2; i++ { // Make time slice runtime.Goshed() fmt.Println("this is main") } }
channel
Communication through pipeline is a data type
package main import ( "fmt" "runtime" ) // Global variables, creating channel s var ch = make(chan int) func Printer(str string) { for _, data := range str { fmt.Printf("%c", data) } fmt.Printf("\n") } func person1() { Printer("hello") ch <- 666 } func person2() { <- ch //Get data from the pipeline and accept it. If there is no data, it will be blocked Printer("world") } func main() { go person1() go person2() for { } } -------------------- // Data exchange package main import ( "fmt" "runtime" ) func main() { ch := make(chan string) go func () { defer fmt.Println("son"); for i := 0; i < 2; i++ { fmt.Pritln("i",i) } ch <- "I'm zixie Cheng" }() str := <- ch fmt.Println('str',str) } -------------- // No buffer = > make(chan type, 0) will be blocked if receive and send are not ready // If the cache make(chan type, capacity) is full, it will be blocked // Close channel close(ch); for { if num, ok := <-ch; ok == true { } else { } } // Ergodic ch for num := range ch { fmt } // one-way pakeage main() func main() { ch := make(chan int) var writenCh chan<- int = ch var readCh <-chan int = ch writeCh <- 666 <- readCh }
timer
pakeage main() import ( "fmt" "time" ) func main() { timer := time.NewTimer(1 * time.Second) // once for { <-time.C fmt.Println("Time out") } } -------------------- pakeage main() import ( "fmt" "time" ) func main() { timer := time.NewTimer(3 * time.Second) go func() { <-timer.C fmt.Println("The subprocess can be printed") } //Reset timer.Reset(1 * time.Second) //stop it timer.Stop() for { } } ----------------------------- // ticker cycle pakeage main() import ( "fmt" "time" ) func main() { ticker := time.NewTicker(1 * time.Second) i := 0 for { <-ticker.C i++ fmt.Println("i = ",i) } }
select
Listening channel
pakeage main import ( "fmt" ) func f1(ch chan<- int, quit <-chan bool) { x, y := 1, 1 for { select { case ch <- x: x, y := y, x +y case flag := <- quit: fmt.Println("exit") return case <-time.After(3 * time.Second) } } } func main() { ch := make(chan int) quit := make(chan bool) go func() { for i := 0; i < 8; i++{ num := <-ch fmt.Println("num =", num) } quit<-true }() f1(ch, quit) }