Learning notes from python to go -- common functions

String function

The common system functions and built-in functions in string are not very different from those in python, and their names are also very similar

**Len function: * * returns the length of the string. Unlike python's len() function, golang is utf-8 encoded, so Chinese characters will become three lengths.

func main() {
    str := "123 Beijing"
    fmt.Println("str len = ",len(str))
}
//str len = 9

**strconv.Atoi: * * string to integer (can be used for user input verification)

**strconv.Itoa: * * integer to string

func main() {
   n,err := strconv.Atoi("123")
   if err != nil {
      fmt.Println("switch views,The error is:",err)
   }else{
      fmt.Println("Convert Chen Kun,The data are:",n)
   }
    
    str := strconv.Itoa(123)
	fmt.Println(str)
}

[] byte(): string to [] byte

string(): [] byte to string

func main() {
    bt := []byte("Emerald flower")
	fmt.Println(bt)
    
    str := string([]byte{97,98,99})
    fmt.Println(str)
}
//[231 191 160 232 138 177]
//abc

strconv. Formatint(): hexadecimal to hexadecimal (similar to int(num,2) in python)

func main() {
	str := strconv.FormatInt(132,2)
	fmt.Println(str)
}
//10000100

strings.Contains(s,substr): judge whether the substring is in the specified string, and return true/false

strings.Count(s,substr): the statistical string contains several substrings and returns int

strings.EqualFold(s1,s2): judge whether the strings are the same, case insensitive (= = case sensitive)

strings.Index(s,substr): returns the subscript of the substring for the first time in the string

strings.LastIndex(s,substr): returns the subscript of the last occurrence of the substring in the string

func main() {
	b := strings.Contains("seafood","food")
	fmt.Println(b)								//true
    
    num := strings.Count("familia","a")
    fmt.Println(num)							//2
    
    fmt.Println(strings.EqualFold("Abc","aBC"))	//true
    
    index := strings.Index("familia","mi")
	fmt.Println(index)							//4
}

strings.Replace(s,old,new,n): python str.replace(), string replacement, n indicates how many to replace (- 1 indicates all)

strings.Split(s,sep): python str.split(), string segmentation

strings. Tolower (s): str.lower() of python, lowercase

strings. Toupper (s): str.upper() of python, uppercase

func main() {
	str := "I am a Chinese from China"
	str2 := strings.Replace(str,"China","Baoji",-1) //I am a Baoji man from Baoji
	fmt.Println(str2)
}

strings.TrimSpace(s): remove the spaces on both sides

strings.Trim(s,sep): remove the characters specified on both sides

strings.TrimLeft(s,sep): remove the specified character on the left

strings. Trimlight (s, SEP): remove the characters specified on the right (equivalent to python's str.lstrip(), str.rstrip(), str.strip())

Date function

There is time in golang Time type, representing time

func main() {
	now := time.Now()	// Get current time
	fmt.Printf("now = %v,type = %T\n",now,now)
    //now = 2021-12-20 23:59:19.1477705 +0800 CST m=+0.006507101,type = time.Time
	fmt.Println("year = ",now.Year())			//Year = 2021
	fmt.Println("month = ",now.Month())			//Month = December
	fmt.Println("month = ",int(now.Month()))	//Month = 12
	fmt.Println("day = ",now.Day())			//Day = 20
	fmt.Println("Time = ",now.Hour())			//Time = 23
	fmt.Println("branch = ",now.Minute())		//Score = 59
	fmt.Println("second = ",now.Second())    	//Seconds = 19
}

Format output:

func main() {
    //fmt output
	fmt.Printf("Current date %d-%d-%d %d:%d:%d \n",now.Year(),now.Month(),now.Day(),
		now.Hour(),now.Minute(),now.Second())
    //Current date: 2021-12-20 23:59:19 
    
    //Method provided by time
    fmt.Printf(now.Format("2006/01/02 15:04:05")) //The time can only be obtained by fixing the writing method. The format can be changed, but the number cannot be changed
    //2021/12/21 00:12:09
}

Sleep: time Sleep

time.Sleep(100*time.Millisecond) //Sleep for 100 milliseconds

Built in function (builtin)

**new: * * used to allocate memory. It is mainly used to allocate value types. It returns pointers

func main() {
	num1 := 100 //int type
	fmt.Printf("type of num1 = %T,value of num1 = %v,address of num1 = %v\n",num1,num1,&num1)
	num2 := new(int) //*int type
	fmt.Printf("type of num2 = %T,value of num2 = %v,address of num2 = %v\n",num2,num2,&num2)
}
//type of num1 = int,value of num1 = 100,address of num1 = 0xc00010e018
//type of num2 = *int,value of num2 = 0xc00010e050,address of num2 = 0xc000108018

**make: * * used to allocate memory, mainly to allocate reference types

var Slice name []type = make([],len,[cap]) //Declare a slice

exception handling

Go language exception handling does not use the try... except... finally mode of python. Throw a panic exception in go, and then catch the exception through recover in defer, and then handle it

  • The first way to write: defer is an anonymous function to catch exceptions
func test()  {
	// defer + recover
	defer func() {
		err := recover() //Built in functions to catch exceptions
		if err != nil {
			fmt.Println("error = ",err)
		}
	}()
	num1 := 10
	num2 := 0
	res := num1/num2
	fmt.Println(res)
}
//error =  runtime error: integer divide by zero
  • The second writing method: write an exception capture function to call
func except() {
	if err := recover();err != nil {
		fmt.Println("error = ",err)
	}
}

func test()  {
	// defer + recover
	defer except()

	num1 := 10
	num2 := 0
	res := num1/num2
	fmt.Println(res)
}

Custom exception

Use errors New and panic built-in functions

  1. errors.New("error description"), returns a value of error type, indicating an error
  2. The panic built-in function receives a value of interface {} type as a parameter. It can accept the variable of error type, output error information and exit the program
func readConf(name string) (err error) {
	if name == "config.ini" {
		//Read...
		return nil
	}else {
		//A custom error was returned
		return errors.New("Error reading file")
	}
}

func test()  {
	err := readConf("config.ing")
	if err != nil{
		//Read file error, output error and terminate the program
		panic(err)
	}
	fmt.Println("test")
}

func main() {
	test()
	fmt.Println("flandre")
}

Keywords: Python Go

Added by lansing on Wed, 23 Feb 2022 04:20:02 +0200