Home > front end >  Is there a way to access string value from a string pointer receiver within it's own method?
Is there a way to access string value from a string pointer receiver within it's own method?

Time:07-25

I wish to do this:

type StateSyncError string

func (se *StateSyncError) Error() string {
    return "state sync error: "   se
}

which fails due to invalid operation: "state sync error: " se (mismatched types untyped string and *StateSyncError).

Is it possible to do somehow? I had hopes of ~ working since it should look at underlying type, but to no avail. Should I just use a struct?

CodePudding user response:

Dereference the pointer and use a type conversion:

func (se *StateSyncError) Error() string {
    return "state sync error: "   string(*se)
}

Testing it:

var se StateSyncError = "foo"
fmt.Println(se.Error())

Output (try it on the Go Playground):

state sync error: foo
  • Related