英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论