How do I get the string value of os.Error? ie. assign to a variable.
The returned error can be treated as a string by either accessing err. Error() , or using the fmt package functions (for example fmt. Println(err) ).
Errors can be returned as nil , and in fact, it's the default, or “zero”, value of on error in Go. This is important since checking if err != nil is the idiomatic way to determine if an error was encountered (replacing the try / catch statements you may be familiar with in other programming languages).
If you have written any Go code you have probably encountered the built-in error type. Go code uses error values to indicate an abnormal state. For example, the os. Open function returns a non-nil error value when it fails to open a file. func Open(name string) (file *File, err error)
Update based on go1 release notes:
Use err.Error() to get the string value.
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!"
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With