Go language variables functions Socks5 proxy example details

  • 2020-06-07 04:39:19
  • OfStack

The declaration of variables in Go is similar to that of JavaScript. Using the var keyword, variables are declared and defined in several forms

1. Variables and constants


//  Declare and initialize 1 A variable 
var m int = 10
//  Declaration initializes multiple variables 
var i, j, k = 1, 2, 3
//  Multiple variable declarations ( Note the use of parentheses )
var(
 no int
 name string
)
//  The declaration does not specify the type and is derived by initializing the value 
var b = true // bool type 
// :=  Implicitly declare variables and assign values 
str := "mimvp.com"  //  Is equivalent to var str string = "mimvp.com"

What is the difference between = and := in Go?

= is an assignment, := is a declaration of a variable and an assignment


// =  Must be used first var Declarations such as: 
var a
a = 100
//  or 
var b = 100
//  or 
var c int = 100
// :=  Is declared and assigned, and the system automatically infer the type, not required var The keyword 
d := 100
// Go There are 1 A special variable is underlined "_"  Indicates that any value assigned to it will be discarded 
_, Ret:= 2, 3  // 2 Assignments are discarded 

The COMPILER in Go is reporting errors for declared but unused variables, so variables must be declared if they are to be used

Go is the same as C. Go also USES semicolons to terminate statements. Unlike C, however, Go's lexical analyzer automatically inserts semicolons while scanning source code using simple rules that eliminate the need for semicolons most of the time

The rule for the Go lexical analyzer to insert a semicolon: a semicolon is inserted automatically if the last token before a new line is an identifier (including words like int and float64), a basic literal such as a numeric value, or one of the following tokens

The Go language typically USES semicolons only in for statements to separate initializers, additions, and deletes. Another situation is when you write multiple statements in line 1, you also need to use semicolons to separate them

Due to the special nature of the Go lexical analyzer in adding semicolons, there are some situations that need to be noted:

You should never put the left curly bracket of a control structure (if, for, switch, or select) in the next line.

If you do this, you insert a semicolon in front of the curly braces, which can lead to unwanted results.

Constants: values that cannot be changed in a program. 1 is generally defined as values, booleans, strings, etc

Format: const constName [type] = val

1). var num = 3 // 实际上 3 也称为常量

2). val can be an expression in the format, but not an expression whose result will be known at runtime

3). Predefined constants: true/false/iota

4). When defining multiple constants, the following method can also be used


const ( 
 constName1 [type] = val1 
 constName2 [type] = val2 
) 

Sample code:


/**
* mimvp.com
* 2017.1.20
*/
//  Declare the package name to which the current file belongs, main is 1 Three packages that can be run independently and generate executable files after compilation  
package main 
import "fmt" //  Import packages  
var id = 123456 
/* 
id2 := 654321 
//  Outside of the function  :=  , an error occurs at compile time, and the local variable declaration should be inside the function 
// non-declaration statement outside function body 
*/ 
const PI = 3.14  //  Constant statement 
//  Each program that can be run independently contains entry functions  main  , as in other languages, but without arguments and return values  
func main() { 
 var num int 
 num = 100 
 fmt.Println(num)  //  The output  100 
 var num1, num2 int 
 num1, num2 = 1, 2 
 fmt.Println(num1, num2) //  The output  1 2 
 var no1, no2 = 3, 4 
 fmt.Println(no1, no2)  //  The output  3 4 
 n1, n2 := 5, 6 
 fmt.Println(n1, n2)  //  The output  5 6 
 _, n := 7, 8 
 fmt.Println(n)    //  The output  8 
 var ( 
  key1 string 
  key2 string 
 ) 
 key1, key2 = "k1", "k2" 
 fmt.Println(key1, key2) //  The output  k1 k2 
 var ( 
  a = 9 
  b = 10 
 ) 
 fmt.Println(a, b)   //  The output  9 10 
 fmt.Println(id)   //  The output  123456 
 fmt.Println(PI)   //  The output  3.14 
 /* 
 PI = 3.1415 
 //  Changing the value of a constant causes an error in compilation  
 // cannot assign to PI 
 // cannot use 3.1415 (type float64) as type ideal in assignment 
 */ 
}

2. Function usage

1) Go language function format


func GetMsg(i int) (str string) {
 fmt.Println(i)
 str = "hello mimvp.com"
 return str
}

Explanation:

func says this is a function

GetMsg is the name of the function

The (i int) function receives one of the int parameters, which are passed in

The str string function returns a return value of type string, which is a return parameter

2) Go language function can return multiple values

The function returns multiple values, which are different from mainstream languages like Java, PHP, and C, but the same as scripting languages like Python and lua


<span style="color:#0000FF;">vim mimvp_func.go</span>
func GetMsg(i int) (str string, err string) {
 fmt.Println(i)
 str = "hello mimvp.com"
 err = "no err"
 return str, err
}
func main() {
 fmt.Println(GetMsg(100))
}

Compile execution:


$ go build mimvp_func.go 
$ ./mimvp_func   
100
hello mimvp.com no err

3) Use of defer

defer means "call on function exit", especially when reading or writing to a file. You need to call close after open and use defer for close


func ReadFile(filePath string)(){
 file.Open(filePath)
 defer file.Close()
  
 if true {
  file.Read()
 } else {
  return false
 }
}

The above code means that close is not called immediately after ES119en.Open, but file.Close () when return false, thus effectively avoiding memory leaks in the C language.

4) Understand panic, recover

Many variables and functions have been covered above, but the use of ES133en-ES134en-ES135en has not been covered

In Go, Panic and Recover are throw and catch in other languages

Sample code:


package main
import "fmt"
func main() {
 f()
 fmt.Println("Returned normally from f.")
}
func f() {
 defer func() {
  if r := recover(); r != nil {
   fmt.Println("Recovered in f", r)
  }
 }()
 fmt.Println("Calling g.")
 g(0)
 fmt.Println("Returned normally from g.")
}
func g(i int) {
 if i > 3 {
  fmt.Println("Panicking!")
  panic(fmt.Sprintf("%v", i))
 }
 defer fmt.Println("Defer in g", i)
 fmt.Println("Printing in g", i)
 g(i + 1)
}

Operation results:


$ ./mimvp-try-catch   
Calling g.
Printing in g 0
Printing in g 1
Printing in g 2
Printing in g 3
Panicking!
Defer in g 3
Defer in g 2
Defer in g 1
Defer in g 0
Recovered in f 4
Returned normally from f.

Panic throws the message and jumps out of the function. Recover receives the information and continues to process it.

So this is an example where you basically know Recover and Panic

Socks5 proxy server


// =  Must be used first var Declarations such as: 
var a
a = 100
//  or 
var b = 100
//  or 
var c int = 100
// :=  Is declared and assigned, and the system automatically infer the type, not required var The keyword 
d := 100
// Go There are 1 A special variable is underlined "_"  Indicates that any value assigned to it will be discarded 
_, Ret:= 2, 3  // 2 Assignments are discarded 
0

conclusion


Related articles: