brianoh
brianoh

Reputation: 3577

A way to get the value of os.Error - string value (Go)

How do I get the string value of os.Error?

That is, assign to a variable.

Upvotes: 39

Views: 36785

Answers (3)

Ekkehard.Horner
Ekkehard.Horner

Reputation: 38775

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!"

Upvotes: 40

peterSO
peterSO

Reputation: 166925

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"

Documentation with a full list of fmt formatting verbs,

fmt package's format verbs

Upvotes: 54

michielbdejong
michielbdejong

Reputation: 1107

You can also use fmt.Sprint(err)

This returns a variable of type string which you can then, for instance, assign to a variable:

message := fmt.Sprint(err)

Upvotes: -1

Related Questions