Day 2 of golang Learning Series: variables, constants, data types and process statements

Time:2022-1-2

 

Following the first day of golang, today we will learn about the variables, constants, data types and control flow statements of golang.

If you have worked on projects in other programming languages (such as JavaScript, Java and python), you actually have a good understanding of variables, constants, data types and control flows.

Variables, also known as “variables”, are quantities that reflect the movement and change of things, such as exchange rate, mortgage interest rate and loan interest rate.

Constants, also known as “constants”, are quantities that reflect the relative static state of things. Once defined, they cannot be changed later, such as pi.

Golang is different from JavaScript and python, but like Java, it is a statically typed programming language, that is, its type needs to be declared before defining a variable or constant

1. Variables

1.1} declare a variable

Variables need to be declared before use, for example

package main

import "fmt"

func main() {
   Var age int // age defaults to 0
   fmt. Printf ("my age is:% d years \ n", age)
   Age = 99 // assign a value to age
   fmt. Printf ("my age is:% d", age)
}

The output is shown in the figure

1.2 automatic derivation of variable types

You can also use another way to deduce the type of variable according to the value

package main

import "fmt"

func main() {
   var age = 99
   fmt. Printf ("my age is:% d years \ n", age)
   age = 100  //
}

Output results

1.3} shorthand definition of variables

There is a more concise way to write

import "fmt"

func main() {
   //fmt.Printf("hello, world\n")
   //var name string
   age := 99
   fmt. Printf ("my age is:% d years \ n", age)
   age = 100
}

1.4 defining multiple variables

During real development, we need to define multiple variables. For example, a user has multiple fields such as name, age, gender, address, city, etc

I define variables in 1.1

package main

import "fmt"

func main() {
   //fmt.Printf("hello, world\n")
   //var name string
   var (
	Name string = "Dong Guangming"
	age      int    =  99
	City string = "Jinling City"
    )
    
   	fmt. Printf ("my name is:% s, age: (% d), city:% s", name, age, city)
}

Output results

1.5} functional variables

This definition is very common in JavaScript. A variable can be of any type, including functions. Golang also supports it. It really integrates the characteristics of several languages, which is not supported by Java

package main

import "fmt"

func main() {
   	//Variables can also be function definitions
   	print := func() {
		var (
	     Name string = "Dong Guangming, DGM"
         age      int    =  99
    	 City string = "Jinling is actually Nanjing"
         )
    
       	fmt. Printf ("my name is:% s, age: (% d), city:% s", name, age, city)
	}
	
	print()
}

Output results

 

2. Constant

Constant definitions are similar to variables, except that there are multiple keywords const

package main

import "fmt"

const (
	Pi    = 3.141592653
	Loading = false
	Name   = "dongguangming"
	Age = 99
)

func main() {
	Const city = "Jinling City"
	fmt.Println(City)
	fmt.Println(Pi)
	fmt.Println(Loading)
	fmt.Println(Name)
    fmt.Println(Age)
	//Const CompanyName: = "a company" // unsupported, unable to compile
}

Output results

Constants can only be character, string, Boolean, or numeric values and cannot be declared using the:= syntax. An untyped constant takes the type needed by its context.

 

3. Data type

There are two types: basic data type and derived data type. Only basic data types are introduced here, and the latter will be introduced separately later

3.1 basic data type

The basic data types include Boolean bool, string, numeric number and complex data types

3.1.1 Boolean

Bool type represents Boolean logic, and its value is either true or false

package main

import "fmt"

func main() {  
    have := true
    nohave := false
    fmt.Println("have:", have, "nohave:", nohave)
    result_and := have && nohave
    fmt.Println("result_and:", result_and)
    result_or := have || nohave
    fmt.Println("result_or:", result_or)
}

In the above code, the variable have is defined and assigned to true and the variable nohave is assigned to false

Variable result_ And is assigned as false, because the logical operator & & returns true only when the values on both sides are true. In the example, only have is true, so the operation result is false.

Variable result_ Or is assigned to true, because the logical operator 𞓜 indicates that as long as one of the values on both sides is true, true will be returned. In the example, have is just true, so the operation result is true.

Execute the above and output the following results

The theoretical analysis is correct

 

3.1.2 string type

A string is a collection of bytes that stores a sequence of characters.

package main

import (  
    "fmt"
)

func main() {  
    First: = "Dong"
    Last: = "Guangming"
    name := first + last
    fmt. Println ("my name is:", name)
}

Output results:

 

3.1.3} numerical type

Numerical subdivision has the following types:

Numeric types:

uint        either 32 or 64 bits,represents 32 or 64 bit unsigned integers depending on the underlying platform,32 bits in 32 bit systems and 64 bits in 64 bit systems( 0 to 4294967295 in 32 bit systems and 0 to 18446744073709551615 in 64 bit systems ).
int         either 32 or 64 bits,represents 32 or 64 bit integers depending on the underlying platform. You should generally be using int to represent integers unless there is a need to use a specific sized integer,32 bits in 32 bit systems and 64 bit in 64 bit systems(-2147483648 to 2147483647 in 32 bit systems and -9223372036854775808 to 9223372036854775807 in 64 bit systems)
uintptr     an unsigned integer large enough to store the uninterpreted bits of
            a pointer value
uint8       the set of all unsigned  8-bit integers (0 to 255)
uint16      the set of all unsigned 16-bit integers (0 to 65535)
uint32      the set of all unsigned 32-bit integers (0 to 4294967295)
uint64      the set of all unsigned 64-bit integers (0 to 18446744073709551615)

int8        the set of all signed  8-bit integers (-128 to 127)
int16       the set of all signed 16-bit integers (-32768 to 32767)
int32       the set of all signed 32-bit integers (-2147483648 to 2147483647)
int64       the set of all signed 64-bit integers
            (-9223372036854775808 to 9223372036854775807)

float32     the set of all IEEE-754 32-bit floating-point numbers
float64     the set of all IEEE-754 64-bit floating-point numbers

complex64   the set of all complex numbers with float32 real and imaginary parts
complex128  the set of all complex numbers with float64 real and imaginary parts

byte        alias for uint8
rune        alias for int32 (represents a Unicode code point)

Integer formula

package main

import (  
    "fmt"
    "unsafe"
)

func main() {  
    var first int = 88
    second := 99
    fmt. Println ("first value =" ", first,", second value = "", second)
    fmt. Printf ("first type is:% T, first size% d", first, unsafe. Sizeof (first)) // type and size of first
    fmt. Printf ("\ nsecond type is:% T, second size% d", second, unsafe. Sizeof (second)) // type and size of second
}

Floating point number

package main

import (  
    "fmt"
)

func main() {  
    first, second := 6.66, 9.99
    fmt. Printf ("type of first is% T, type of second is% t \ n", first, second)
    sum := first + second
    diff := first - second
    fmt. Println ("sum yes", sum, "subtraction yes", diff)
}

Complex number calculation

package main

import (  
    "fmt"
)

func main() {  
    first := complex(5, 7)
    second := 8 + 27i
    sum := first + second
    fmt. Println ("sum of complex numbers:", sum)
    diff := first - second
    fmt. Println ("complex subtraction:", diff)
    product := first * second
    fmt. Println ("plural multiplication:", product)
}

 

Since the numerical type may be used for mathematical calculation of parameters, but golang itself has no automatic conversion function, the converted data type needs to be displayed manually

package main

import (  
    "fmt"
)

func main() {  
    first := 66      //int
    second := 77.7    //float64
    //Sum: = first + second // int + float64 not allowed. The compilation fails, so the following conversion is required. Golang has no automatic conversion function
    sum := first + int(second) //second is converted to int

    fmt.Println(sum)
}

But there are exceptions

package main

import (  
    "fmt"
)

func main() {  
    first := 10
    var second float64 = float64(first) //this statement will not work without explicit conversion
    fmt.Println("second:", second)
}

Output results

There is no flag 10.0f after conversion like other languages

 

4. Process statement

There are three types: if condition / if else, loop loop, and switch

4.1  if, if else

4.1.1 if statement

Used to specify whether the corresponding code block should be executed. Syntax structure:

if(condition) {
  //Execute code logic when condition is true
}

for example

package main
import "fmt"

func main() {
    Var country = "China"
	var age = 18
	If (country = = "China" & & age > = 18){
		fmt. Printf ("you're an adult, it's time to make money \ n")
	}
}

Output results

Note that, You can omit the parentheses () from an if statement in Golang, but the curly braces {} are mandatory – 

Note that in the world of golang, you can not use the parenthesis () after if, but the curly braces after if are necessary, for example

If country = = "China" & & age > = 18{
		fmt. Printf ("you're an adult, it's time to make money \ n")
}

4.1.2 if else statement

An IF statement can be used with an else statement block. When the condition in the if is false, the logical code of the else statement block will be executed and the code structure will be simplified

if condition {
  // code to be executed if the condition is true
} else {
  // code to be executed if the condition is false
}

Sample code

package main
import "fmt"

func main() {
	var age = 18
	if age >= 18 {
		fmt. Println ("well, you are already an adult, not a child!!!")
	} else {
		fmt. Println ("sorry, you're under age!")
	}
}

Output results

4.1.3 if else if chain

If statements can have multiple else statement blocks, such as

package main
import "fmt"

func main() {
	var age = 12
	if age>=6 && age < 11 {
		fmt. Println ("you may be in primary school");
	} else if age >= 12 && age < 15 {
		fmt. Println ("you may be in junior high school");
	} else if age >= 15 && age < 18 {
		fmt. Println ("you may be in high school")
	} else {
		fmt. Println ("went to college")
	}
}

4.1.4 if phrase sentence

The if statement allows you to include a short declaration statement before a conditional expression

package main
import "fmt"

func main() {
   if first := 10; first%2 == 0 {
     fmt. Printf (% d is even \ n, first)
   } 

   if second := 15; second%2 == 0 {
  fmt. Printf (% d is an even number \ n, second)
} else {
  fmt. Printf (% d is odd \ n, second)
}
}

Note: the variable declared in the short statement is only available inside the if block and it’s else or else if branches,

If you’re using a short statement, then you can’t use parentheses. The following code will report an error

If (second: = 15; second% 2 = = 0) {// syntax error ()
    fmt. Printf (% d is an even number \ n, second)
} else {
    fmt. Printf (% d is odd \ n, second)
}

 

4.2} loop

Loop is used to repeatedly run code blocks. Golang only needs a loop statement L: the for loop. The structure is as follows

for initialization; condition; increment {
  //Circulatory body
}

Initialization statement initialization is executed once before the first iteration of the loop. In each iteration, the condition is checked. If the condition evaluates to true, the loop body is executed. Otherwise, the loop terminates. The increment statement increment is executed at the end of each iteration. Example code:

package main
import "fmt"

func main() {
	for i := 0; i < 10; i++ {
		fmt.Printf("%d ", i)
	}
}

Look, it doesn’t need parentheses like Java.

Special note: initialization and increment statements in the for loop are optional and can be omitted, as shown below

Omit the initialization statement

package main

import "fmt"

func main() {
	i := 2
	for ; i <= 10; i += 2 {
		fmt.Printf("%d ", i)
	}
}

Omit the incremental statement

package main

import "fmt"

func main() {
	i := 2
	for i <= 20 {
		fmt.Printf("%d ", i)
		i *= 2
	}
}

Finally, you can omit the condition from the for loop in golang, which will give you an infinite loop

package main

func main() {
    for {
      //Loop body statement
    }
}

 

Terminate break statement

You can use the break statement to break the loop before it terminates normally, such as

package main

import "fmt"

func main() {
	for num := 1; num <= 50; num++ {
		if num%4 == 0 && num%7 == 0 {
			fmt. Printf ("number of cycles terminated:% d \ n", Num)
			break
		}
		fmt. Printf ("number of loops not terminated:% d \ n", Num)
	}
}

output

 

continue Statement

The continue statement is used to stop the operation of the loop body halfway and continue to the next iteration of the loop.

package main
import "fmt"

func main() {
	for num := 1; num <= 10; num++ {
		if num%2 == 0 {
			continue;
		}
		fmt.Printf("%d \n", num)
	}
}

Output results

 

Wireless loop infinite loop

The syntax structure is as follows

for {  
  //Circulatory body
}

package main

import "fmt"

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

4.3   Switch 

The switch statement accepts an expression and matches it with a list of possible situations. Once a match is found, it executes the code block specified in the matching case.

Sample code

package main

import (  
    "fmt"
)

func main() {  
    age := 8
    switch age {
    case 8:
        fmt. Println ("pupil")
    case 13:
        fmt. Println ("junior high school students")
    case 17:
        fmt. Println ("high school student")
    case 19:
        fmt. Println ("college student")
    case 21:
        fmt. Println ("social personage")
    default: //default case
        fmt. Println ("children")
    }
}

Special attention:

Go evaluates all switch cases one by one from top to bottom until the case is successful. When the case succeeds, it runs the code block specified in the case and then stops (no other cases are evaluated).

This is in contrast to other languages (such as C, C + + and Java), where you explicitly need to insert a break statement after the body of each case to stop evaluating subsequent cases.

If none of the cases is successful, the default case is executed.

 

4.3.1 switch and short statements

Like if, switch can also include a short declaration statement before a conditional expression. as follows

package main

import (
	"fmt"
)

func main() {
	switch dayOfWeek := 6; dayOfWeek {
	case 1:
		fmt. Println ("Monday")
	case 2:
		fmt. Println ("Tuesday")
	case 3:
		fmt. Println ("Wednesday")
	case 4:
		fmt. Println ("Thursday")
	case 5:
		fmt. Println ("Friday")
	case 6:
		{
			fmt. Println ("Saturday")
			fmt. Println ("weekend ha ha!")
		}
	case 7:
		{
			fmt. Println ("Sunday")
			fmt. Println ("weekend ha ha!")
		}
	default:
		fmt. Println ("the end of the world")
	}
}

Note: the only difference is that variables declared by short statements are only available inside the switch block.

 

4.3.2 multiple expressions in case

You can include multiple expressions by separating them with commas.

package main

import (  
    "fmt"
)

func main() {  
    dayOfWeek  := "2"
    switch dayOfWeek {
    case "1", "2", "3", "4", "5": //multiple expressions in case
        fmt. Println ("working day")
    default:
        fmt. Println ("rest day")
    }
}

4.3.3 switch without expression

The expression in the switch is optional and can be omitted. If the expression is omitted, the switch is considered true, and the authenticity of each case expression is evaluated and the corresponding code block is executed.

package main

import (  
    "fmt"
)

func main() {  
    num := 75
    switch { // expression is omitted
    case num >= 0 && num <= 50:
        fmt. Println ("greater than or equal to 0 and less than or equal to 50")
    case num >= 51 && num <= 100:
        fmt. Println ("greater than or equal to 50 and less than or equal to 100")
    case num >= 101:
        fmt. Println ("greater than 100")
    }
}

 

4.3.4 type switch

Switch can also be used to discover the dynamic types of interface variables. This type switch uses the syntax of type assertions with the keyword type in parentheses

If switch declares a variable in an expression, the variable will have a corresponding type in each clause. In this case, it is also customary to reuse names. In fact, in each case, a new variable with the same name but different types is declared.

The sample code is interesting

package main

import (
	"fmt"
)

func main() {
	var t interface{}
	t = 10
	
	switch t := t.(type) {
	default:
		fmt.Printf("unexpected type %T\n", t) // %T prints whatever type t has
	case bool:
		fmt.Printf("boolean %t\n", t) // t has type bool
	case int:
		fmt.Printf("integer %d\n", t) // t has type int
	case *bool:
		fmt.Printf("pointer to boolean %t\n", *t) // t has type *bool
	case *int:
		fmt.Printf("pointer to integer %d\n", *t) // t has type *int
	}
}

Output results

 

4.3.5 combine multiple switch cases (combined with cases 4.3.1 and 4.3.2 above)

The code is as follows

package main
import "fmt"

func main() {
	switch dayOfWeek := 5; dayOfWeek {
		case 1, 2, 3, 4, 5:
			fmt. Println ("working day")
		case 6, 7:
			fmt. Println ("rest")
		default:
			fmt. Println ("the end of the world")		
	}
}

 

Conclusion: the knowledge of linguistics is interlinked. It can be finished in less than 11 days. Grammar doesn’t take much time to learn. It’s like many code farmers in the park (the knowledge points of Java itself and the knowledge points in the spring ecosystem are not all learned, and even some concepts don’t know the Tao, which doesn’t affect their work). 60% ~ 80% of the knowledge points are enough for ordinary development, Golang is more like a hodgepodge, with the taste of C and JavaScript, and sometimes looks like java!!!

 

reference resources:

  1.  What’s the Go language really good for?  https://www.infoworld.com/article/3198928/whats-the-go-language-really-good-for.html

  2. Golang for loop https://m.youtube.com/watch?feature=youtu.be&v=rO11gboBY3M&fbclid=IwAR0LS6yzU0DksIEkl8neo6pDT31WsmFUwCZoU77RYrcpvcEYhtO22zSCpOs

  3. Golang Cheatsheet: Variables https://ado.xyz/blog/golang-cheatsheet-variables/

  4. Default Values for Go Types https://ado.xyz/byte/default-values-for-golang-types/

  5. Programmering i Go  https://unixsheikh.com/programmering-i-go/

Recommended Today

Explanation of websocket heartbeat reconnection

Recently, websocket has been used in the development of applet. The applet provides corresponding native API, which is different from H5 API. Therefore, some mature class libraries of popular H5 are difficult to use, and the native API has some defects, so it implements a set of heartbeat reconnection mechanism by itself. First, let’s briefly […]