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

huangapple go评论86阅读模式
英文:

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

问题

我希望这样做:

type StateSyncError string

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

但是由于invalid operation: "state sync error: " + se (mismatched types untyped string and *StateSyncError),它失败了。

有没有办法解决这个问题?我原本希望~可以工作,因为它应该查看底层类型,但是没有成功。我应该只使用一个结构体吗?

英文:

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?

答案1

得分: 2

将指针解引用并使用类型转换:

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

测试代码:

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

输出结果(在Go Playground上尝试):

state sync error: foo
英文:

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

huangapple
  • 本文由 发表于 2022年7月25日 17:27:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/73106883.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定