os.Error - string value (Golang)

后端 未结 2 1140

How do I get the string value of os.Error? ie. assign to a variable.

相关标签:
2条回答
  • 2021-02-11 15:35

    For example,

    package main
    
    import (
        "errors"
        "fmt"
    )
    
    func main() {
        err := errors.New("an error message")
        s := err.Error()
        fmt.Printf("type: %T; value: %q\n", s, s)
    }
    

    Output:

    type: string; value: "an error message"
    
    0 讨论(0)
  • 2021-02-11 15:50

    Update based on go1 release notes:

    Use err.Error() to get the string value.

    Example:

    package main
    
    import (
        "fmt"
        "errors"
        "runtime"
    )
    
    func main() {
        err := errors.New("use of err.String() detected!")
        s := err.Error()
        fmt.Printf(
           "version: %s\ntypes: %T / %T\nstring value via err.Error(): %q\n",
           runtime.Version(), err, s, s)
    }
    

    output:

    go run main102.go
    version: go1.0.2
    types: *errors.errorString / string
    string value via err.Error(): "use of err.String() detected!"
    
    0 讨论(0)
提交回复
热议问题