Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

os.Error - string value (Golang)

Tags:

go

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

like image 872
brianoh Avatar asked May 16 '11 02:05

brianoh


People also ask

How do I return a string error in Golang?

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) ).

What is err != Nil in Golang?

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).

What does err mean in Golang?

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)


2 Answers

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!" 
like image 38
Ekkehard.Horner Avatar answered Oct 07 '22 00:10

Ekkehard.Horner


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" 
like image 92
peterSO Avatar answered Oct 06 '22 22:10

peterSO