当前位置:网站首页>[golang learning notes 1.7] functions in golang should be used
[golang learning notes 1.7] functions in golang should be used
2022-07-20 12:17:00 【Who made the promise】
defer
In the function , Programmers often create resources ( such as : Database connection , Locks, etc. ), In order to execute the function after , Release resources in time ,defer You can use it ( Delay mechanism )
String commonly used system functions
- Statistical string length : len(str) ; Return the length of string or array
- String traversal , At the same time, deal with problems containing Chinese : arr:=[]run(str); Convert string to slice
Example :
str:=" Hello ,abc"
for i := 0; i <len(str); i++ {
fmt.Printf("i: %c\n", str[i])
}
Printout
i: äi: ½i: i: åi: ¥i: ½i: ,i: ai: bi: c
Because it contains Chinese characters , If you don't convert , The printout will be disordered , It's not what we want
str:=" Hello ,abc"
arr:=[]rune(str)
for i := 0; i <len(arr); i++ {
fmt.Printf("i: %c ", arr[i])
}
Printout
i: you i: good i: , i: a i: b i: c
- String to integer : strconv.Atoi(str)
//strconv.Atoi Yes 2 Return values , One is the value of successful conversion , One is the error return of unsuccessful conversion
num,err:=strconv.Atoi("123")
if err != nil{
fmt.Printf("err: %v\n", err)
}else{
fmt.Printf("num: %v\n", num)
}
- Integer to string : strconv.Itoa(int)
- String rotation byte: []byte(str)
- byte Turn the string :str=string([]byte{97,98,99})
- Hexadecimal conversion :str=strconv.FormatInt(int64,int);int64 The number to be converted ;int The base number to convert 2,8,10 The result of conversion is the corresponding string
- Determine whether the string is in another string :strings.Contains(“hello,world”,“world”) If in Then return to true otherwise false
- Determine how many strings there are in another string :strings.Count(“hello,world”,“world”) Return the number of contains
- Case insensitive judgment :strings.EqualFold(“hello,world”,“world”) return bool type
- Use case sensitive judgment abc==Abc == Equivalent to all equals
- Returns the subscript value of the first occurrence of one string in another string : str:=strings.Index(“hello,world”,“world”) return int type
- Returns the subscript value of the last occurrence of one string in another string : str:=strings.LastIndex(“hello,world”,“world”) return int type
- String substitution :strings.Replace(str,str2,str3,num)
// The first parameter is the string that needs to be matched
// The second parameter is the replacement string
// The third is the string to be replaced
// The fourth is if there are multiple strings to replace , Then it represents the quantity to be replaced -1 Replace for all
num:=strings.Replace("hhhhh,world","h"," Beijing ",1)
- Cut the string into an array of strings according to the specified characters :strings.Split(“h,h,h,h,h,world”,“,”)
// according to , Division ; Return string array slice
num:=strings.Split("h,h,h,h,h,world",",")
fmt.Printf("type=%T,num=%v\n", num,num)
Print the results
type=[]string,num=[h h h h h world]
- Case conversion function of letters in string strings.ToLower(“GO”); Turn lowercase .strings.ToUpper(“go”); Turn capitalization .
- Remove the spaces on the left and right sides of the string :strings.TrimSpace(" go ");
- Remove the specified characters on the left and right sides of the string :strings.Trim(“!go!”,“!”);
- Remove the specified character on the left of the string :strings.TrimLeft(“!go!”,“!”);
- Remove the specified character on the right of the string :strings.TrimRight(“!go!”,“!”);
- Determines whether the string begins with the specified string :strings.HasPrefix(“https://go.com”,“https”); return bool type
- Determines whether a string ends with the specified string :strings.HasSuffix(“GO.jpg”,“jpg”); return bool type
- Subsequent complement …jpg
- go Document address :https://studygolang.com/pkgdoc
Time and date correlation function
- Initialization time now()
// Now Return to the current local time
now:=time.Now()
fmt.Printf("now: %v\n", now)
- year
now:=time.Now()
fmt.Printf(" year : %v\n", now.Year())
- month
now:=time.Now()
fmt.Printf(" month : %v\n", now.Month())// English month
fmt.Printf(" month : %v\n", int(now.Month()))// Digital month
- Japan
now:=time.Now()
fmt.Printf(" Japan : %v\n", now.Day())
- when
now:=time.Now()
fmt.Printf(" when : %v\n", now.Hour())
- branch
now:=time.Now()
fmt.Printf(" branch : %v\n", now.Minute())
- second
now:=time.Now()
fmt.Printf(" second : %v\n", now.Second())
- Format time
// Now Return to the current local time
now:=time.Now()
// Return the current time in the format of year month day hour minute second 【2006/01/02 15:04:05 Is a fixed value ; immutable 】
// origin 2006 by Golang Time of birth ,15 It's afternoon 3 spot .
// Ways to help memory :1 month 2 Japan 3 spot 4 branch 5 second ,2006 year ,-7 The time zone , Is precisely 1234567.
//2006/01/02 15/04/05 You can freely combine the return time
date:=now.Format("2006-01-02 15:04:05")
fmt.Printf("date: %v\n", date)
- Time unit
Nanosecond Duration = 1 //1 nanosecond
Microsecond = 1000 * Nanosecond //1 subtle =1000* nanosecond
Millisecond = 1000 * Microsecond //1 millisecond =1000*1 subtle
Second = 1000 * Millisecond //1 second =1000*1 millisecond
Minute = 60 * Second //1 minute =60*1 second
Hour = 60 * Minute //1 Hours =60*1 minute
- Get the timestamp
// Now Return to the current local time
now:=time.Now()
unix:=now.Unix()
unixnano:=now.UnixNano()
fmt.Printf("unix: %v\n", unix)
fmt.Printf("unixnano: %v\n", unixnano)
// Print the results
// unix: 1658126367
//unixnano: 1658126367931653600
Error handling
- defer,panic,recover have access to defer+recover To handle exceptions
// Define an anonymous function
defer func () {
//recover() Function can catch exceptions
err:=recover()
// If an exception is caught, the exception information is output
if err !=nil{
fmt.Printf("err: %v\n", err)
}
}()
- panic Output the error and terminate the program
panic(" To terminate the program , And output error ")
- Custom error
package main
import (
"errors"// Reference package
"fmt"
)
func main(){
err:= errors.New(" I made a custom error ")
fmt.Printf("err: %v\n", err)
}
边栏推荐
- Summary of database optimization methods and problems
- The El input input box needs to support multiple inputs
- 高斯数学——看动画学奥数
- Style attribute operation of DOM series
- 23. Network principle - key protocols in tcp/ip four layer model (2)
- Okaleido or get out of the NFT siege, are you optimistic about it?
- Optimization case 2: select scalar subquery and sort main query
- 【微信小程序】input输入框(87/100)
- C#入门系列(二十四) -- 密封类和静态类
- Reptile exercises (III)
猜你喜欢
Design and Simulation of infinite impulse response digital filter based on MATLAB
MySQL learning notes - View
【小程序】小游戏到底是个啥?
故障006:连接排序去重结果不如人愿
Beauty live broadcast first use ldr6028 wireless microphone sound quality transmission OTG charging continuous output
22、网络原理——TCP/IP四层模型之中的重点协议(1)
Cloud foundry developer course (lfd232) 3 core concepts
DOM series change element content
Why learn istio
云呐-fsu动环监控单元,fsu动环监控单元是什么
随机推荐
读论文:(YOLOv1)You Only Look Once:Unified, Real-Time Object Detection
Solution to the first game of 2022 Niuke multi school league
Distributed notes (04) - redis of distributed locks (distributed lock implementation, locking process, unlocking process, deadlock prevention, correct and incorrect locking and unlocking Implementatio
科学动画片等
Methods of querying Oracle11g logs, database audit, record troubleshooting
1381: City Road (Dijkstra)
Instructions for bertpretrainedmodel in transformers
iTextSharp快速使用指南
HCIA-R&S自用笔记(11)VRP文件系统、系统管理
什么是反向代理?
基于MATLAB的无限脉冲响应数字滤波器的设计与仿真
Gamefi industry declines but not out | June report
[wechat applet] from form (88/100)
MySQL learning notes - stored procedures and functions
Optimization case 2: select scalar subquery and sort main query
DOM series change element content
数据库优化方式和问题汇总篇
Vs2017 opencv3.4.2 is compiled into x86 through the release version source code
Flask请求数据和获取响应
Why learn istio