This is the fourth day of my participation in the August Challenge. For details, see:August is more challenging

ptr

Pointers in GO have two core concepts

  • A pointer to a type that allows modification of data of this type. Data can be passed directly to the pointer without copying the data. A pointer to a type cannot be offset or manipulated.
  • Slice, consisting of the original pointer to the starting element, the number of elements, and the capacity.

Pointer address and pointer type

  • Pointer address, each pointer variable, which stores the memory address of the value. In other words, this memory address takes up 4 bytes of space on a 32-bit machine and 8 bytes of space on a 64-bit machine. The size of this memory address does not matter
  • Pointer type,

Get pointer address “&”

ptr := &aaa

Where aaa is a value and PTR is the assigned pointer argument

Get the value “*” of the pointer

str := *ptr

Use * to get the contents of the value to which the pointer points

Assign and get the value of a pointer

Package main import "FMT" func main() {var cat string = "I love egg fried rice" catAddress := &cat catValue := *catAddress Println("", &cat, catAddress, catValue)} 0x14000010240 0x14000010240 I love egg-fried riceCopy the code

The address operator & and the value operator * are a pair of complementary operators. & retrieves the address, and * retrieves the value that the address points to based on the address.

Modify the value of the pointer

Package main import "FMT" func main() {var cat string = "I love egg fried rice" catAddress := &cat catValue := *catAddress fmt.Println("", &cat, catAddress, catValue) a:=1 b:=2 swap(&a,&b) fmt.Println("",a,b) } func swap(a, b *int) { t := *a *a = *b *b = t }Copy the code

Another way to create a pointer

New (type)

Println(* STR) :=new (string) * STR = FMT.Println(* STR)Copy the code

Usage scenarios of Pointers

  1. Direct manipulation of the address to which the pointer points completely changes the value of the parameter, so it can be used in method passing. The input parameter of the direct method is passed a pointer type of the parameter, and the parameter is changed in the method. It will cause the caller to change it as well so the usual function argument list is*xxxAs a parameter
package main

import (
	"errors"
	"fmt"
)

func testMap(strs *[]string) (bool, error) {

	for _, str := range *strs {

		fmt.Println(str)
	}
	*strs = append(*strs, "Black")
	return true, errors.New("No error result information.")}func main(a) {
	strs := []string{"White"."Little red"."Little blue"}
	b, err := testMap(&strs)

	fmt.Printf("", b, err)
	fmt.Printf("", strs)
}

Copy the code

Conditional statements

if

use

If a < 20 {/* if a < 20 {/* if the condition is true, execute the following statement */ fmt.printf ("a < 20\n")}Copy the code

switch

Switch {case grade == "A" : FMT.Printf(" 高 级! \n") case grade == "B", grade == "C" : FMT.Printf(" good \n") case grade == "D" : FMT.Printf(" good \n") case grade == "F": FMT.Printf(" fail \n") default: FMT.Printf(" fail \n"); }Copy the code

select

Select randomly executes a runnable case. If there are no cases to run, it blocks until there are cases to run. A default clause should always run.

   select {
      case i1 = <-c1:
         fmt.Printf("received ", i1, " from c1\n")
      case c2 <- i2:
         fmt.Printf("sent ", i2, " to c2\n")
      case i3, ok := (<-c3):  // same as: i3, ok := <-c3
         if ok {
            fmt.Printf("received ", i3, " from c3\n")
         } else {
            fmt.Printf("c3 is closed\n")
         }
      default:
         fmt.Printf("no communication\n")
   }
Copy the code

Looping statements

for

Three ways of use

  1. For numerical initialization; Cycle judge; Numerical transformation {logical processing}Consistent with forI in Java
     for i := 0; i <= 10; i++ {
                 sum += i
     }
    Copy the code
  2. For loop judge {logical statement (where numerical transformation is performed)}Assign a value before use. That is, divide the first method into three pieces
         sum := 1
         for ; sum <= 10; {
                 sum += sum
         }
    Copy the code
  3. for { }
    Sum := 0 for {sum++}Copy the code

break; Statement breaks the current for loop or breaks out of the switch loop

continue; Statement to jump out of the current cycle and proceed to the next cycle

Function/method

Definition of a function

structure

Func method name ([parameter list]) [return value type] {logical processing}Copy the code

For example,

Func mulit100(val *int32) (bool,error){val=val*100 return (true, errors.new (" no error message returned "))}Copy the code

Parameter list and return value types are not required

Calling a function

Return value Result = Function name (argument list)Copy the code

Built-in function

The name of the instructions
close Used to close a channel
Len, cap len Used to return the length or quantity of a type (string, array, slice, map, and pipe); Cap is capacity and is used to return the maximum capacity of a certain type (for slices and maps only)
The new, make Both new and make are used to allocate memory: new is used for value types and user-defined types, such as custom structures. The built-in function new allocates memory space for an element type filled with zero values and returns its address, a value of a pointer type. Make is used for built-in reference types (slices, maps, and pipes) to create a slice of a specified element type, length, and capacity. The e capacity part can be omitted, in which case the capacity will equal the length. They are used like functions, but take types as arguments: new(type), make(type). New (T) allocates the zero value of type T and returns its address, that is, a pointer to type T). It can also be used for basic types: v := new(int). Make (T) returns the initialized value of type T, so it does more work than new. New () is a function, don’t forget the parentheses
Copy, append Copy returns the length of the copy, which automatically takes the shortest length (min(len(SRC), len(DST))). Append appends elements to slice
Panic, recover Both are used as an error handling mechanism, as panic is thrown, which immediately stops execution of the current function and runs all the deferred functions, then panic is thrown up until the program carsh. Recover is used to capture and return the error object submitted by panic. A call to panic throws a value that can be captured by calling the recover function. The main difference is that even if the current Goroutine is in panic state, or if there are active emergencies in the current Goroutine, the recovery call may not be able to retrieve the values thrown by those active emergencies.
Print and println Underlying print function
The complex, real imag To create and manipulate complex numbers, iMAg returns the real part of complex, and real returns the imaginary part of complex
delete Example Delete the value corresponding to the key from the map

Anonymous functions

func(a) {// Define an anonymous
    //func body} ()// The curly braces are followed by () to indicate a function call.
Copy the code