Chapter 2, Go-Basic Grammar

Chapter 2, Go-Basic Grammar

2.1. Variable definition

(1) The first program helloworld

package main

import(
	"fmt"
)

func main() {
	fmt.Println("helloworld")
}

(2) The initial value of the variable

If you define a variable without assigning a value, there will be a default initial value

package main

import(
	"fmt"
)

func variableZeroValue(){
	//Define two variables without assignment
	var a int
	var s string
	fmt.Printf("%d %q\n",a,s)//formatted output
}

func main() {
	fmt.Println("helloworld")
	variableZeroValue()//a,s initial value: 0 ""
}

(3) The definition and assignment of variables 

package main

import(
	"fmt"
)

func variableInitialValue(){
	//The definition and assignment of variables
	var a, b int = 3,4
	var s string = "derek"
	fmt.Println(a,b,s)
}

func variableShorter(){
	//Use a colon
	d,e,f := 5,false,"zhang"
	fmt.Println(d,e,f)
}

func main() {
	variableInitialValue()//3 4 derek
	variableShorter()//5 false zhang
}

(4) Use var() to centrally define variables

package main

import(
	"fmt"
)

//Centralized definition of variables
var (
	aa = 2
	bb = true
	cc = "jack"
)

func main() {

	fmt.Println(aa,bb,cc)//2 true jack
}

 summary

  • Use var keyword: var s1,s2 string = "zhang","derek"
  • Let the compiler automatically select the type: var a,b,i,s1,s2 = true,false,3,"hello","world"
  • Use a colon to define variables: a,b,i,s1,s2 := true,false,3,"hello","world", can only be used within a function

2.2. Built-in variable types

(1) Type

  • bool,string
  • (u)int,(u)int8,(u)int16,(u)int32,(u)int64,unitptr
  • byte,rune
  • float32,float64,complex64,comlex128

(2) Forced type conversion

package main

import(
	"fmt"
	"math"
)

func main() {
	var a,b int = 3,4
	//Sqrt must receive float64 type, first convert the sum of squares of a and b to float64 type, and then convert the result to int type
	var c int = int(math.Sqrt(float64(a*a + b*b)))
	fmt.Println(c)//5
}

2.3. Constants and Enumerations

The const value can be used as various types if the type is not specified, and the type can also be specified.

(1) The definition of constants

package main

import(
	"fmt"
)

func main() {
	//If the type is not specified, it can be used as various types
	const a,b = 3,4
	//Specify as string type, then it is the specified type
	const str string = "derek"
	//You can put parentheses without writing const every time
	const (
		c = false
		d = "jack"
	)
	fmt.Println(a,b,str)//3 4 derek
	fmt.Println(c,d)//false jack
}

(2) Enumeration type

package main

import(
	"fmt"
)

func main() {
	const (
		java = 0
		python =1
		golang = 2
	)
	fmt.Println(java,python,golang)//0 1 2
}

(3) Use iota self-value-added enumeration type

package main

import(
	"fmt"
)

func main() {
	const (
		java = iota//iota means this group of const self-value added
		python
		golang
		javascript
	)
	fmt.Println(java,python,golang,javascript)//0 1 2 3
}

2.4. Conditional statements

(1) if statement

No parentheses are required in the condition of the if statement

package main

import(
	"fmt"
	"io/ioutil"
)

func main() {
	const filename = "C:\\Users\\86158\\Desktop\\awesomeProject\\src\\abc.txt"
	//ioutil.ReadFile: returns two values, one is the content of the read file, the other is the error message
	//The condition of if can be assigned
	if contents,err := ioutil.ReadFile(filename); err != nil{
		fmt.Println(err)
	}else {
		fmt.Printf("%s\n",contents)
	}
	//The scope of the variable assigned in the if condition is in the if statement. If you access it outside of the if like the following, an error will be reported
	fmt.Println(contents)
}

(2) switch statement

  • There can be no expression after switch
  • switch does not need to break
  • You can switch multiple conditions directly
package main

import(
	"fmt"
)

func grade(score int) string{
	g := ""
	switch {
	case score <0 || score> 100:
		//Error message
		panic(fmt.Sprintf("Wrong score: %d",score))
	case score <60:
		g = "D"
	case score <80:
		g = "C"
	case score <90:
		g = "B"
	case score <= 100:
		g = "A"
 	}
	return g
}

func main() {
	fmt.Println(grade(2))
	fmt.Println(grade(70))
	fmt.Println(grade(83))
	fmt.Println(grade(101))//panic: Wrong score: 101
}

2.5. Loop

for

  • No parentheses are required in the for condition
  • The initial condition, end condition, and increment expression can be omitted in the for condition
package main

import "fmt"

func main() {
	sum := 0
	for i :=1; i <= 100; i++{
		sum += i
	}
	fmt.Println(sum)
}

2.6. Functions

Features:

  • The return value type is written at the end
  • Multiple values ​​can be returned
  • Functions can be used as parameters
  • There are no default and optional parameters

(1) Basic usage

package main

import "fmt"

//Function name (function parameter, parameter type) return value type
func eval(a,b int, op string) int {
	switch op {
	case "+":
		return a + b
	case "-":
		return a-b
	case "*":
		return a * b
	case "/":
		return a/b
	default:
		//Error message
		panic("unsupport operation: "+ op)
	}
}

func main() {
	fmt.Println(eval(3,5,"+"))//8
	fmt.Println(eval(3,5,"*"))//15
	fmt.Println(eval(3,5,"gg"))//panic: unsupport operation: gg
}

(2) Two return values

package main

import "fmt"

//Returns two values
func div(a,b int) (q,r int){
	return a/b, a% b
}

func main() {
	//Receive two values
	q,r := div(13,3)
	fmt.Println(q,r)//4 1
}

 Only receive a return value

package main

import "fmt"

//Returns two values
func div(a,b int) (q,r int){
	return a/b, a% b
}

func main() {
	//If you only want to receive a return value, you can use "_"
	q,_ := div(13,3)
	fmt.Println(q)//4 
}
Reference: https://cloud.tencent.com/developer/article/1478605 Chapter 2, Go-Basic Grammar-Cloud + Community-Tencent Cloud