Does Go provide a standard or de facto way to handle errors within a single statement (i.e. inline error handling)?

王林
Release: 2024-02-09 22:50:10
forward
468 people have browsed it

Go 是否提供了标准或事实上的方法来处理单个语句中的错误(即内联错误处理)?

Does the Go language provide a standard or de facto way of handling errors within a single statement, i.e. inline error handling? This is a question often asked by many Go language beginners. The answer is yes, the Go language does provide a concise and effective way to handle errors in a single statement. In the Go language, you can use the short declaration form of the if statement, combined with the multi-return value feature of the function, to implement inline error handling. This approach is both concise and flexible, and can improve the readability and maintainability of the code. At the same time, the Go language also provides some standard library functions and error handling functions to handle more complex error scenarios. Overall, the Go language provides a complete and easy-to-use method for handling errors in a single statement.

Question content

In Rust, the Result type can be thought of as the (val, err) pattern in Go, where it can appear The statement "expands" immediately, and does not require the complexity of dedicating multiple rows to this task. For example, let's say we have a function foo that returns a number or an error. In Rust, handling this error (without ignoring it) can be as simple as:

let x = foo().unwrap() + 1;
Copy after login

In Go, the recommended approach seems to be:

x, err := Foo()
if err != nil {
    panic(err)
}
x = x + 1
Copy after login

Does Go provide a standard way to handle errors immediately in a single statement like Rust does? Or should I stick with a homegrown solution?

My temporary solution is:

func unwrap[T any](val T, err error) T {
    if err != nil {
        panic(err)
    } else {
        return val
    }
}
Copy after login
<小时/>

I'm a little surprised by the excess. None of the five linked questions are duplicates, and none of them specifically answer my question. Some may even seem completely unrelated. I think this is because my title was worded incorrectly. I've reworded the title to be more relevant to my actual problem. Thankfully, u/norbjd answered my question adequately.

Workaround

As @mkopriva said in the comments, there is no built-in way to do this in Go. However, you can find this pattern in many libraries under the name Must:

There is an

public proposal on Go to add a generic must.Do method, but there is no concrete content yet.

The currently recommended approach is to use generics to define Must methods in your code (as of Go 1.18), like you do:

func Must[T any](v T, err error) T {
    if err != nil {
        panic(err)
    }
    return v
}
Copy after login

and use it like this:

import (
    "errors"
    "fmt"
)

func Foo() (int, error) {
    return 1, nil
}

func Bar() (int, error) {
    return 0, errors.New("some error")
}

func main() {
    foo := Must(Foo())
    fmt.Println(foo)
    bar := Must(Bar()) // this will panic with "some error"
    fmt.Println(bar)
}
Copy after login

There have been attempts to create libraries to provide this method, such as wingyplus/must, but as the repo points out, based on the Go philosophy:

So you can define your own methods in each project, or use these types of libraries until Must be integrated into the Go standard library (if it ever is).

The above is the detailed content of Does Go provide a standard or de facto way to handle errors within a single statement (i.e. inline error handling)?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:stackoverflow.com
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!