This is the sixth day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

Recently, I have been learning the go language principle and practice with the small volume. Because there is no go language foundation, I followed the rookie tutorial to learn the basic grammar of go language foundation – rookie tutorial. Go Basic Language notes, there will be two, this is the second one.

1 array

package main

import "fmt"

func main(a) {
   var n [10]int /* n is an array of length 10 */
   var i,j int

   /* Initializes elements for array n */        
   for i = 0; i < 10; i++ {
      n[i] = i + 100 /* Sets the element to I + 100 */
   }

   /* Prints the value of each array element */
   for j = 0; j < 10; j++ {
      fmt.Printf("Element[%d] = %d\n", j, n[j] )
   }
}
Copy the code

result

Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109
Copy the code
package main

import "fmt"

func main(a) {
   var i,j,k int
   // Quickly initialize an array while declaring it
   balance := [5]float32{1000.0.2.0.3.4.7.0.50.0}

   /* Outputs the array element */.for i = 0; i < 5; i++ {
      fmt.Printf("balance[%d] = %f\n", i, balance[i] )
   }
   
   balance2 := [...]float32{1000.0.2.0.3.4.7.0.50.0}
   /* Prints the value of each array element */
   for j = 0; j < 5; j++ {
      fmt.Printf("balance2[%d] = %f\n", j, balance2[j] )
   }

   // Initialize elements with indexes 1 and 3
   balance3 := [5]float32{1:2.0.3:7.0}  
   for k = 0; k < 5; k++ {
      fmt.Printf("balance3[%d] = %f\n", k, balance3[k] )
   }
}
Copy the code

result

Balance [0] = 1000.000000 Balance [1] = 2.000000 Balance [2] = 3.400000 Balance [3] = 7.000000 Balance [4] = 50.000000 Balance2 [0] = 1000.000000 Balance2 [1] = 2.000000 Balance2 [2] = 3.400000 Balance2 [3] = 7.000000 Balance2 [4] = 50.000000 Balance3 [0] = 0.000000 balance3[1] = 2.000000 Balance3 [2] = 0.000000 balance3[3] = 7.000000 balance3[4] = 0.000000Copy the code

2 a pointer

package main

import "fmt"

func main(a) {
   var a int= 20   /* Declare the actual variable */
   var ip *int        /* Declare a pointer variable */

   ip = &a  /* The storage address of the pointer variable */

   fmt.Printf("The address of variable A is: %x\n", &a  )

   /* The storage address of the pointer variable */
   fmt.Printf("IP variable stored pointer address: %x\n", ip )

   /* Use Pointers to access values */
   fmt.Printf("* IP variable value: %d\n", *ip )
}
Copy the code

result

The address of the a variable is: 20818a220 the address of the pointer to the IP variable is: 20818a220 * the value of the IP variable is: 20Copy the code
  • Null pointer
package main

import "fmt"

func main(a) {
   var  ptr *int

   fmt.Printf("PTR value: %x\n", ptr  )
}
// null pointer judgment
//if(ptr ! = nil) /* PTR is not null */
//if(ptr == nil)    /* ptr 是空指针 */
Copy the code

result

The value of PTR is 0Copy the code

Three structures

  • Defining structure
package main

import "fmt"

type Books struct {
   title string
   author string
   subject string
   book_id int
}


func main(a) {

    // Create a new structure
    fmt.Println(Books{"The language"."www.runoob.com"."Go Language Tutorial".6495407})

    // The key => value format can also be used
    fmt.Println(Books{title: "The language", author: "www.runoob.com", subject: "Go Language Tutorial", book_id: 6495407})

    // Fields ignored are 0 or empty
   fmt.Println(Books{title: "The language", author: "www.runoob.com"})}Copy the code

result

Go www.runoob.com Go language tutorial 6495407} {Go language www.runoob.com Go language tutorial 6495407} {Go language www.runoob.com 0}Copy the code
  • Access structure members
package main

import "fmt"

type Books struct {
   title string
   author string
   subject string
   book_id int
}

func main(a) {
   var Book1 Books        /* Declare Book1 as Books */
   var Book2 Books        /* Declare Book2 as Books */

   /* book 1 description */
   Book1.title = "The language"
   Book1.author = "www.runoob.com"
   Book1.subject = "Go Language Tutorial"
   Book1.book_id = 6495407

   /* book 2 description */
   Book2.title = "Python tutorial"
   Book2.author = "www.runoob.com"
   Book2.subject = "Python Language Tutorial"
   Book2.book_id = 6495700

   /* Prints Book1 information */
   fmt.Printf( "Book 1 title : %s\n", Book1.title)
   fmt.Printf( "Book 1 author : %s\n", Book1.author)
   fmt.Printf( "Book 1 subject : %s\n", Book1.subject)
   fmt.Printf( "Book 1 book_id : %d\n", Book1.book_id)

   /* Prints Book2 information */
   fmt.Printf( "Book 2 title : %s\n", Book2.title)
   fmt.Printf( "Book 2 author : %s\n", Book2.author)
   fmt.Printf( "Book 2 subject : %s\n", Book2.subject)
   fmt.Printf( "Book 2 book_id : %d\n", Book2.book_id)
}
Copy the code

result

Book 1 Title: Go Book 1 Author: www.runoob.com Book 1 Subject: Go Book_id: 6495407 Book 2 title: Book 2 Author: www.runoob.com Book 2 Subject: Python Tutorial Book 2 Book_id: 6495700Copy the code
  • Structure is passed as a function parameter
package main

import "fmt"

type Books struct {
   title string
   author string
   subject string
   book_id int
}

func main(a) {
   var Book1 Books        /* Declare Book1 as Books */
   var Book2 Books        /* Declare Book2 as Books */

   /* book 1 description */
   Book1.title = "The language"
   Book1.author = "www.runoob.com"
   Book1.subject = "Go Language Tutorial"
   Book1.book_id = 6495407

   /* book 2 description */
   Book2.title = "Python tutorial"
   Book2.author = "www.runoob.com"
   Book2.subject = "Python Language Tutorial"
   Book2.book_id = 6495700

   /* Prints Book1 information */
   printBook(Book1)

   /* Prints Book2 information */
   printBook(Book2)
}

func printBook( book Books ) {
   fmt.Printf( "Book title : %s\n", book.title)
   fmt.Printf( "Book author : %s\n", book.author)
   fmt.Printf( "Book subject : %s\n", book.subject)
   fmt.Printf( "Book book_id : %d\n", book.book_id)
}
Copy the code

result

Book Title: Go Book Author: www.runoob.com Book Subject: Go Book_id: 6495407 Book Title: Book Author: www.runoob.com Book Subject: Python Book book_id: 6495700Copy the code
  • Structure pointer
package main

import "fmt"

type Books struct {
   title string
   author string
   subject string
   book_id int
}

func main(a) {
   var Book1 Books        /* Declare Book1 as Books */
   var Book2 Books        /* Declare Book2 as Books */

   /* book 1 description */
   Book1.title = "The language"
   Book1.author = "www.runoob.com"
   Book1.subject = "Go Language Tutorial"
   Book1.book_id = 6495407

   /* book 2 description */
   Book2.title = "Python tutorial"
   Book2.author = "www.runoob.com"
   Book2.subject = "Python Language Tutorial"
   Book2.book_id = 6495700

   /* Prints Book1 information */
   printBook(&Book1)

   /* Prints Book2 information */
   printBook(&Book2)
}
func printBook( book *Books ) {
   fmt.Printf( "Book title : %s\n", book.title)
   fmt.Printf( "Book author : %s\n", book.author)
   fmt.Printf( "Book subject : %s\n", book.subject)
   fmt.Printf( "Book book_id : %d\n", book.book_id)
}
Copy the code

result

Book Title: Go Book Author: www.runoob.com Book Subject: Go Book_id: 6495407 Book Title: Book Author: www.runoob.com Book Subject: Python Book book_id: 6495700Copy the code

4 slices

  • Len () and cap() functions
package main

import "fmt"

func main(a) {
   var numbers = make([]int.3.5)

   printSlice(numbers)
}

func printSlice(x []int){
   fmt.Printf("len=%d cap=%d slice=%v\n".len(x),cap(x),x)
}
Copy the code

result

len=3 cap=5 slice=[0 0 0]
Copy the code
  • Empty (nil) slice
package main

import "fmt"

func main(a) {
   var numbers []int

   printSlice(numbers)

   if(numbers == nil){
      fmt.Printf("The slice is empty.")}}func printSlice(x []int){
   fmt.Printf("len=%d cap=%d slice=%v\n".len(x),cap(x),x)
}
Copy the code

result

Len =0 Cap =0 slice=[] The slice is emptyCopy the code
  • Slice the interception
package main

import "fmt"

func main(a) {
   /* Create a slice */
   numbers := []int{0.1.2.3.4.5.6.7.8}  
   printSlice(numbers)

   /* Prints the original slice */
   fmt.Println("numbers ==", numbers)

   /* Print the subslice from index 1(included) to index 4(not included)*/
   fmt.Println("numbers[1:4] ==", numbers[1:4])

   /* The default lower limit is 0*/
   fmt.Println("numbers[:3] ==", numbers[:3])

   /* The default limit is len(s)*/
   fmt.Println("numbers[4:] ==", numbers[4:])

   numbers1 := make([]int.0.5)
   printSlice(numbers1)

   /* Print the subslice from index 0(included) to index 2(not included) */
   number2 := numbers[:2]
   printSlice(number2)

   /* Print the subslice from index 2(included) to index 5(not included) */
   number3 := numbers[2:5]
   printSlice(number3)

}

func printSlice(x []int){
   fmt.Printf("len=%d cap=%d slice=%v\n".len(x),cap(x),x)
}
Copy the code

result

len=9 cap=9 slice=[0 1 2 3 4 5 6 7 8]
numbers == [0 1 2 3 4 5 6 7 8]
numbers[1:4] == [1 2 3]
numbers[:3] == [0 1 2]
numbers[4:] == [4 5 6 7 8]
len=0 cap=5 slice=[]
len=2 cap=9 slice=[0 1]
len=3 cap=7 slice=[2 3 4]
Copy the code
  • Append () and copy()
package main

import "fmt"

func main(a) {
   var numbers []int
   printSlice(numbers)

   /* Allow to append empty slices */
   numbers = append(numbers, 0)
   printSlice(numbers)

   /* Adds an element */ to the slice
   numbers = append(numbers, 1)
   printSlice(numbers)

   /* Add multiple elements */
   numbers = append(numbers, 2.3.4)
   printSlice(numbers)

   /* Create slices numbers1 is double the size of previous slices */
   numbers1 := make([]int.len(numbers), (cap(numbers))*2)

   /* Copy the contents of numbers to numbers1 */
   copy(numbers1,numbers)
   printSlice(numbers1)  
}

func printSlice(x []int){
   fmt.Printf("len=%d cap=%d slice=%v\n".len(x),cap(x),x)
}
Copy the code

result

len=0 cap=0 slice=[] len=1 cap=1 slice=[0] len=2 cap=2 slice=[0 1] len=5 cap=6 slice=[0 1 2 3 4] len=5 cap=12 slice=[0 1 2, 3, 4]Copy the code

5 range

package main
import "fmt"
func main(a) {
    // We use range to find the sum of a slice. Using arrays is similar to this
    nums := []int{2.3.4}
    sum := 0
    for _, num := range nums {
        sum += num
    }
    fmt.Println("sum:", sum)
    // Using range on an array passes in the index and value variables. In the example above we do not need to use the ordinal of the element, so we omit the "_" whitespace. Sometimes we do need to know its index.
    for i, num := range nums {
        if num == 3 {
            fmt.Println("index:", i)
        }
    }
    //range can also be used in map key-value pairs.
    kvs := map[string]string{"a": "apple"."b": "banana"}
    for k, v := range kvs {
        fmt.Printf("%s -> %s\n", k, v)
    }
    Range can also be used to enumerate Unicode strings. The first argument is the index of the character, and the second is the character (the Unicode value) itself.
    for i, c := range "go" {
        fmt.Println(i, c)
    }
}
Copy the code

result

sum: 9
index: 1
a -> apple
b -> banana
0 103
1 111
Copy the code

6 Map

package main

import "fmt"

func main(a) {
    var countryCapitalMap map[string]string /* Create a collection */
    countryCapitalMap = make(map[string]string)

    /* map inserts key-value pairs, capital of each country */
    countryCapitalMap [ "France" ] = "Paris"
    countryCapitalMap [ "Italy" ] = "Rome"
    countryCapitalMap [ "Japan" ] = "Tokyo"
    countryCapitalMap [ "India " ] = "New Delhi"

    /* Output map values with keys */
    for country := range countryCapitalMap {
        fmt.Println(country, "The capital is.", countryCapitalMap [country])
    }

    /* Check if the element exists in the collection */
    capital, ok := countryCapitalMap [ "American" ] /* if true, it exists, otherwise it does not exist */
    /*fmt.Println(capital) */
    /*fmt.Println(ok) */
    if (ok) {
        fmt.Println("The capital of America is.", capital)
    } else {
        fmt.Println("There is no capital of America.")}}Copy the code

result

The capital of France is Paris. The capital of Italy is Rome. The capital of Japan is TokyoCopy the code
  • The delete () function
package main

import "fmt"

func main(a) {
        /* Create map */
        countryCapitalMap := map[string]string{"France": "Paris"."Italy": "Rome"."Japan": "Tokyo"."India": "New delhi"}

        fmt.Println("Original map")

        /* Print the map */
        for country := range countryCapitalMap {
                fmt.Println(country, "The capital is.", countryCapitalMap [ country ])
        }

        /* Delete the element */ delete(countryCapitalMap, "France")
        fmt.Println("The French entry was deleted.")

        fmt.Println("Map after element deletion")

        /* Print the map */
        for country := range countryCapitalMap {
                fmt.Println(country, "The capital is.", countryCapitalMap [ country ])
        }
}
Copy the code

result

The original map shows India as the capital of New Delhi, France as the capital of Paris, Italy as the capital of Tokyo The capital of India is New DelhiCopy the code

Recursive function

  • factorial
package main

import "fmt"

func Factorial(n uint64)(result uint64) {
    if (n > 0) {
        result = n * Factorial(n- 1)
        return result
    }
    return 1
}

func main(a) {  
    var i int = 15
    fmt.Printf("%d factorial is %d\n", i, Factorial(uint64(i)))
}
Copy the code

result

The factorial of 15 is 1307674368000Copy the code
  • Fibonacci numbers
package main

import "fmt"

func fibonacci(n int) int {
  if n < 2 {
   return n
  }
  return fibonacci(n2 -) + fibonacci(n- 1)}func main(a) {
    var i int
    for i = 0; i < 10; i++ {
       fmt.Printf("%d\t", fibonacci(i))
    }
}
Copy the code

result

0    1    1    2    3    5    8    13    21    34
Copy the code

8 Data type conversion

package main

import "fmt"

func main(a) {
   var sum int = 17
   var count int = 5
   var mean float32
   
   mean = float32(sum)/float32(count)
   fmt.Printf("Mean = %f\n",mean)
}
Copy the code

result

The value of mean is 3.400000Copy the code
Copy the code

result

Copy the code

9 Language Interface

  • The Go language provides another data type, the interface, which defines all common methods together, and any other type that implements those methods implements the interface.
package main

import (
    "fmt"
)

type Phone interface {
    call()
}

type NokiaPhone struct{}func (nokiaPhone NokiaPhone) call(a) {
    fmt.Println("I am Nokia, I can call you!")}type IPhone struct{}func (iPhone IPhone) call(a) {
    fmt.Println("I am iPhone, I can call you!")}func main(a) {
    var phone Phone

    phone = new(NokiaPhone)
    phone.call()

    phone = new(IPhone)
    phone.call()

}
Copy the code

result

I am Nokia, I can call you!
I am iPhone, I can call you!
Copy the code

10 Error Handling

  • The Go language provides a very simple error handling mechanism through a built-in error interface.
package main

import (
    "fmt"
)

// Define a DivideError structure
type DivideError struct {
    dividee int
    divider int
}

// Implement the 'error' interface
func (de *DivideError) Error(a) string {
    strFormat := ` Cannot proceed, the divider is zero. dividee: %d divider: 0 `
    return fmt.Sprintf(strFormat, de.dividee)
}

// Defines a division function of type 'int'
func Divide(varDividee int, varDivider int) (result int, errorMsg string) {
    if varDivider == 0 {
            dData := DivideError{
                    dividee: varDividee,
                    divider: varDivider,
            }
            errorMsg = dData.Error()
            return
    } else {
            return varDividee / varDivider, ""}}func main(a) {

    // Normal condition
    if result, errorMsg := Divide(100.10); errorMsg == "" {
            fmt.Println("100/10 =", result)
    }
    // An error message is returned when the divisor is zero
    if _, errorMsg := Divide(100.0); errorMsg ! ="" {
            fmt.Println("errorMsg is: ", errorMsg)
    }

}
Copy the code

result

100/10 =  10
errorMsg is:  
    Cannot proceed, the divider is zero.
    dividee: 100
    divider: 0
Copy the code

11 concurrent

  • The Go language supports concurrency, so all you need to do is open Goroutine with the Go keyword.

Goroutine is a lightweight thread, and goroutine scheduling is managed by the Golang runtime.

package main

import (
        "fmt"
        "time"
)

func say(s string) {
        for i := 0; i < 5; i++ {
                time.Sleep(100 * time.Millisecond)
                fmt.Println(s)
        }
}

func main(a) {
        go say("world")
        say("hello")}Copy the code

result

world
hello
hello
world
world
hello
hello
world
world
hello
Copy the code
  • Channel
package main

import "fmt"

func sum(s []int, c chan int) {
        sum := 0
        for _, v := range s {
                sum += v
        }
        c <- sum // Send sum to channel C
}

func main(a) {
        s := []int{7.2.8.9 -.4.0}

        c := make(chan int)
        go sum(s[:len(s)/2], c)
        go sum(s[len(s)/2:], c)
        x, y := <-c, <-c // Receive from channel C

        fmt.Println(x, y, x+y)
}
Copy the code

result

17 12-5Copy the code
  • Channel buffer
package main

import "fmt"

func main(a) {
    // We define a buffered channel that can store integer types
        // The buffer size is 2
        ch := make(chan int.2)

        // Since CH is a buffered channel, we can send two data simultaneously
        // You don't need to synchronize the data immediately
        ch <- 1
        ch <- 2

        // Get both data
        fmt.Println(<-ch)
        fmt.Println(<-ch)
}
Copy the code

result

1
2
Copy the code
  • Go traverses channels and closes channels
package main

import (
        "fmt"
)

func fibonacci(n int, c chan int) {
        x, y := 0.1
        for i := 0; i < n; i++ {
                c <- x
                x, y = y, x+y
        }
        close(c)
}

func main(a) {
        c := make(chan int.10)
        go fibonacci(cap(c), c)
        // The range function iterates over each data received from the channel, since C is sending 10
        // The channel is closed after the data, so here our range function receives 10 data
        // Then it's over. If the c channel above is not closed, then the range function is not
        // will end and block on the 11th data.
        for i := range c {
                fmt.Println(i)
        }
}
Copy the code

result

0
1
1
2
3
5
8
13
21
34
Copy the code