How does Golang function return value handle errors?

WBOY
Release: 2024-04-14 10:09:01
Original
337 people have browsed it

Go functions use the error type to represent errors. The caller can determine whether the function executed successfully by checking the value of error. Error handling methods include: using the if statement or the check function of the errchk package. For example: use if statement to handle errors: if err != nil { fmt.Println(err) }; use errchk package to handle errors: errchk.Check(err) // If err is not nil, print an error and exit the program.

Golang 函数返回值如何处理错误?

#How does the Go function return value handle errors?

In Go, functions can use the error type to represent errors. When a function returns an error, the caller can determine whether the function executed successfully by checking the value of error.

In order to handle the error returned by the function, we can use the if statement or the check function under the errchk package.

Use the if statement

Use the if statement to handle errors is the most common method. Example:

func divide(a, b int) (int, error) {
    if b == 0 {
        return 0, errors.New("division by zero")
    }
    return a / b, nil
}

func main() {
    result, err := divide(10, 2)
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Println(result)
    }
}
Copy after login

Using the errchk package

errchk The package provides a check function to simplify error handling. Example:

import "github.com/kisielk/errchk"

func main() {
    result, err := divide(10, 2)
    errchk.Check(err)  // 如果 err 不为 nil,则打印错误并退出程序

    fmt.Println(result)
}
Copy after login

Practical case

The following is a practical case using error handling, which implements a file reading function:

import (
    "bufio"
    "bytes"
    "errors"
    "fmt"
    "io"
)

// readFile 读取给定文件的内容,并返回一个字节切片
func readFile(path string) ([]byte, error) {
    f, err := os.Open(path)
    if err != nil {
        return nil, fmt.Errorf("os.Open: %w", err)  // 使用 fmt.Errorf 包装错误
    }
    defer f.Close()  // 使用 defer 语句在函数返回前关闭文件

    buf := new(bytes.Buffer)
    scanner := bufio.NewScanner(f)
    for scanner.Scan() {
        buf.WriteString(scanner.Text())
        buf.WriteByte('\n')
    }
    if err := scanner.Err(); err != nil {
        return nil, fmt.Errorf("scanner.Err: %w", err)
    }

    return buf.Bytes(), nil
}

func main() {
    data, err := readFile("data.txt")
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Println(string(data))
    }
}
Copy after login

The above is the detailed content of How does Golang function return value handle errors?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!