当前位置:网站首页>Chapter 8 exception handling, string handling and file operation
Chapter 8 exception handling, string handling and file operation
2022-04-23 03:27:00 【Python code doctor】
exception handling
error Interface
Go The language introduces a standard pattern for error handling , namely error Interface , It is Go The type of interface built into the language , This interface is defined as follows :
type error interface {
Error() string
}
Go Standard library code package for languages errors Provide users with the following methods :
package errors
type errorString struct {
text string
}
func New(text string) error {
return &errorString{
text}
}
func (e *errorString) Error() string {
return e.text
}
The other can generate error The method of type value is to call fmt In bag Errorf function :
package fmt
import "errors"
func Errorf(format string, args ...interface{
}) error {
return errors.New(Sprintf(format, args...))
}
Sample code :
import (
"errors"
"fmt"
)
func main() {
var err1 error = errors.New("a normal err1")
fmt.Println(err1) //a normal err1
var err2 error = fmt.Errorf("%s", "a normal err2")
fmt.Println(err2) //a normal err2
}
Function usually returns error information in the last return value :
import (
"errors"
"fmt"
)
func Divide(a, b float64) (result float64, err error) {
if b == 0 {
result = 0.0
err = errors.New("runtime error: divide by zero")
return
}
result = a / b
err = nil
return
}
func main() {
r, err := Divide(10.0, 0)
if err != nil {
fmt.Println(err) // Error handling runtime error: divide by zero
} else {
fmt.Println(r) // Use the return value
}
}
panic
In general , The way to report error status to program users can be to return an extra error Type values .
however , When encountering an unrecoverable error state , If the array access is out of bounds 、 Null pointer references, etc , These runtime errors can cause painc abnormal . At this time , The above error handling methods are obviously not suitable for . On the contrary , In general ,<font color=#FF0000 We should not call panic Function to report common errors , It should only be used as a way to report fatal errors . When something that shouldn't have happened , We should call panic.
generally speaking , When panic When an exception occurs , The program will break , And immediately execute the goroutine( It can be understood as thread first , The function delayed in (defer Mechanism ). And then , The program crashes and outputs log information . The log information includes panic value And function call stack trace information .
Not all panic Exceptions come from the runtime , Call the built-in panic The function also raises panic abnormal ;panic Function takes any value as an argument .
string manipulation
String is often used in development , Including user input , Database read data, etc , We often need to split strings 、 Connect 、 Switching, etc , We can go through Go In the standard library strings and strconv Two functions in the package .
String manipulation
The following functions come from strings package , Here are some functions that I usually use , Please refer to the official document for more details .
Contains
func Contains(s, substr string) bool
function : character string s Include in substr, return bool value
Sample code :
fmt.Println(strings.Contains("seafood", "foo"))
fmt.Println(strings.Contains("seafood", "bar"))
fmt.Println(strings.Contains("seafood", ""))
fmt.Println(strings.Contains("", ""))
// Running results :
//true
//false
//true
//true
Join
func Join(a []string, sep string) string
function : String Links , hold slice a adopt sep link
Sample code :
s := []string{
"foo", "bar", "baz"}
fmt.Println(strings.Join(s, ", "))
// Running results :foo, bar, baz
Index
func Index(s, sep string) int
function : In string s Search for sep Where it is , Return position value , No return found -1
Sample code :
fmt.Println(strings.Index("chicken", "ken"))
fmt.Println(strings.Index("chicken", "dmr"))
// Running results :
// 4
// -1
Repeat
func Repeat(s string, count int) string
function : repeat s character string count Time , Finally return the duplicate string
Sample code :
fmt.Println("ba" + strings.Repeat("na", 2))
// Running results :banana
Replace
func Replace(s, old, new string, n int) string
function : stay s In a string , hold old Replace the string with new character string ,n Indicates the number of replacements , Less than 0 Means replace all
Sample code :
fmt.Println(strings.Replace("oink oink oink", "k", "ky", 2))
fmt.Println(strings.Replace("oink oink oink", "oink", "moo", -1))
// Running results :
//oinky oinky oink
//moo moo moo
Split
func Split(s, sep string) []string
function : hold s String according to sep Division , return slice
Sample code :
fmt.Printf("%q\n", strings.Split("a,b,c", ","))
fmt.Printf("%q\n", strings.Split("a man a plan a canal panama", "a "))
fmt.Printf("%q\n", strings.Split(" xyz ", ""))
fmt.Printf("%q\n", strings.Split("", "Bernardo O'Higgins"))
// Running results :
//["a" "b" "c"]
//["" "man " "plan " "canal panama"]
//[" " "x" "y" "z" " "]
//[""]
Trim
func Trim(s string, cutset string) string
function : stay s The head and tail of the string are removed cutset Specified string
Sample code :
fmt.Printf("[%q]", strings.Trim(" !!! Achtung !!! ", "! "))
// Running results :["Achtung"]
Fields
func Fields(s string) []string
function : Remove s The space character of a string , And return according to the space division slice
Sample code :
fmt.Printf("Fields are: %q", strings.Fields(" foo bar baz "))
// Running results :Fields are: ["foo" "bar" "baz"]
String conversion
The string conversion function is in strconv in , The following is just a list of some commonly used .
Append
Append A series of functions convert integers to strings , Add to existing byte array .
str := make([]byte, 0, 100)
str = strconv.AppendInt(str, 4567, 10) // With 10 Add base mode
str = strconv.AppendBool(str, false)
str = strconv.AppendQuote(str, "abcdefg")
str = strconv.AppendQuoteRune(str, ' single ')
fmt.Println(string(str)) //4567false"abcdefg"' single '
Format
Format A series of functions convert other types to strings .
Sample code :
a := strconv.FormatBool(false)
b := strconv.FormatInt(1234, 10)
c := strconv.FormatUint(12345, 10)
d := strconv.Itoa(1023)
fmt.Println(a, b, c, d) //false 1234 12345 1023
Parse
Parse A series of functions convert strings to other types .
Sample code :
package main
import (
"fmt"
"strconv"
)
func checkError(e error) {
if e != nil {
fmt.Println(e)
}
}
func main() {
a, err := strconv.ParseBool("false")
checkError(err)
b, err := strconv.ParseFloat("123.23", 64)
checkError(err)
c, err := strconv.ParseInt("1234", 10, 64)
checkError(err)
d, err := strconv.ParseUint("12345", 10, 64)
checkError(err)
e, err := strconv.Atoi("1023")
checkError(err)
fmt.Println(a, b, c, d, e) //false 123.23 1234 12345 1023
}
File operations
Create and open files
There are two ways to create a new file :
func Create(name string) (file *File, err Error)
Create a new file based on the filename provided , Return a file object , Default permissions are 0666 The file of , The returned file object is readable and writable .
func NewFile(fd uintptr, name string) *File
Create the corresponding file according to the file descriptor , Return a file object
Open the file in two ways :
func Open(name string) (file *File, err Error)
This method opens a name called name The file of , But it's read-only , The internal implementation actually calls OpenFile.
func OpenFile(name string, flag int, perm uint32) (file *File, err Error)
Open name as name The file of ,flag It's the way it's opened , read-only 、 Reading and writing, etc ,perm It's authority
Writing documents
func (file *File) Write(b []byte) (n int, err Error)
write in byte Type of information to file
func (file *File) WriteAt(b []byte, off int64) (n int, err Error)
Start writing... At the specified location byte Type information
func (file *File) WriteString(s string) (ret int, err Error)
write in string Information to file
Reading documents
func (file *File) Read(b []byte) (n int, err Error)
Read data to b in
func (file *File) ReadAt(b []byte, off int64) (n int, err Error)
from off Start reading data to b in
Delete file
func Remove(name string) Error
Call this function to delete the filename name The file of
Case study : Copy files
Sample code :
package main
import (
"fmt"
"io"
"os"
)
func main() {
args := os.Args // Get all parameters entered by the user
// If the user doesn't type , Or the number of parameters is not enough , Then call this function to prompt the user
if args == nil || len(args) != 3 {
fmt.Println("useage : xxx srcFile dstFile")
return
}
srcPath := args[1] // Get the first parameter of the input
dstPath := args[2] // Get the second parameter of the input
fmt.Printf("srcPath = %s, dstPath = %s\n", srcPath, dstPath)
if srcPath == dstPath {
fmt.Println(" Source and destination file names cannot be the same ")
return
}
srcFile, err1 := os.Open(srcPath) // open the source file
if err1 != nil {
fmt.Println(err1)
return
}
dstFile, err2 := os.Create(dstPath) // Create destination file
if err2 != nil {
fmt.Println(err2)
return
}
buf := make([]byte, 1024) // Slice buffer
for {
// Read content from source file ,n Is the length of the contents of the read file
n, err := srcFile.Read(buf)
if err != nil && err != io.EOF {
fmt.Println(err)
break
}
if n == 0 {
fmt.Println(" The file is finished ")
break
}
// Slice off
tmp := buf[:n]
// Write the read content to the destination file
dstFile.Write(tmp)
}
// Close file
srcFile.Close()
dstFile.Close()
}
版权声明
本文为[Python code doctor]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204220619244145.html
边栏推荐
- . NETCORE sets the API post mode, which can accept parameters directly in parentheses
- Course design of Database Principle -- material distribution management system
- Utgard connection opcserver reported an error caused by: org jinterop. dcom. common. JIRuntimeException: Access is denied. [0x800
- Chapter 8 of C language programming (fifth edition of Tan Haoqiang) is good at using pointer exercises to analyze and answer
- Detailed explanation of socket programming send() and recv() functions
- Can you answer the questions that cannot be answered with a monthly salary of 10k-20k?
- MySql关键字GROUP_CONCAT,组合连接查询
- When migrating tslib_ setup: No such file or directory、ts_ open: No such file or director
- 超好用的Excel异步导出功能
- 批量下載文件----壓縮後再下載
猜你喜欢
Course design of Database Principle -- material distribution management system
TCP three handshakes and four waves
Redis(17) -- Redis缓存相关问题解决
移植tslib时ts_setup: No such file or directory、ts_open: No such file or director
[vs Code] solve the problem that the jupyter file displays exceptions in vs code
打卡:4.22 C语言篇 -(1)初识C语言 - (11)指针
MySQL query specifies that a row is sorted to the first row
General testing technology [1] classification of testing
Visual programming - Experiment 2
Knowledge of software testing~
随机推荐
月薪10k-20k都无法回答的事务问题,你会吗?
软件测试相关知识~
MySql分组查询规则
TCP three handshakes and four waves
Detailed explanation of socket programming send() and recv() functions
2022 group programming ladder simulation match 1-8 are prime numbers (20 points)
IOTOS物联中台对接海康安防平台(iSecure Center)门禁系统
Supersocket is Use in net5 - concept
Seminar playback video: how to improve Jenkins' ability to become a real Devops platform
浅学一下I/O流和File类文件操作
批量下載文件----壓縮後再下載
Build websocket server in. Net5 webapi
Explanation keyword of MySQL
EasyUI's combobox implements three-level query
Log4net is in Net core usage
2021-08-31
Docker pulls MySQL and connects
超好用的Excel异步导出功能
JSON related
Use of ADB command [1]