当前位置:网站首页>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
边栏推荐
- C set
- AWS from entry to actual combat: creating accounts
- socket编程 send()与 recv()函数详解
- Preview of converting doc and PDF to SWF file
- MySql分组查询规则
- The fourth operation
- 场景题:A系统如何使用B系统的页面
- Quartz. Www. 18fu Used in net core
- Peut recevoir plusieurs paramètres de type de données - paramètres variables
- 你真的懂hashCode和equals吗???
猜你喜欢

Log4net is in Net core usage

Codeforces round 784 (Div. 4) (AK CF (XD) for the first time)

Code forces round # 784 (DIV. 4) solution (First AK CF (XD)

Translation of l1-7 matrix columns in 2022 group programming ladder Simulation Competition (20 points)

Super easy to use asynchronous export function of Excel
![Use of ADB command [1]](/img/e6/fb8fd6956c226f75b831f8eb46277f.png)
Use of ADB command [1]

2022 group programming ladder game simulation L2-4 Zhezhi game (25 points)
![[mock data] fastmock dynamically returns the mock content according to the incoming parameters](/img/1e/c4aad49d16fb21a19865ba75128e43.png)
[mock data] fastmock dynamically returns the mock content according to the incoming parameters

C set

Unity knowledge points (ugui)
随机推荐
Unity Basics
IDEA查看历史记录【文件历史和项目历史】
QT learning summary
软件测试相关知识~
Knowledge of software testing~
MySQL grouping query rules
可以接收多種數據類型參數——可變參數
2022 团体程序设计天梯赛 模拟赛 L2-1 盲盒包装流水线 (25 分)
Configure automatic implementation of curd projects
Unity games and related interview questions
Explanation keyword of MySQL
C-11 problem h: treasure chest 2
MySql关键字GROUP_CONCAT,组合连接查询
MySql分组查询规则
Chapter 9 of C language programming (fifth edition of Tan Haoqiang) analysis and answer of exercises for users to establish their own data types
Romantic silhouette of L2-3 of 2022 group programming ladder Simulation Competition (25 points)
JS implementation of new
Flink实时数仓项目—DWS层设计与实现
Generate QR code through zxing
Super easy to use [general excel import function]