英文:
How to call String method on empty interface directly?
问题
我知道的唯一解决方案是使用fmt.Sprint或类似的函数。我已经查看了builtin包,但它只有error接口,string只是一个普通类型,不是接口。
英文:
The only solution I know is using fmt.Sprint or similar functions. I already look into builtin package but it has only error interface, string is just a normal type, not interface.
答案1
得分: 0
如@volker所提到的,你不能这样做,因为空接口没有方法。
请注意:如果存在Stringer接口,fmt.Sprint、fmt.Sprintf等会首先调用它。这是一种优雅的方式。
在类型断言之后调用stringer接口的示例。
var a SomeType
if v, ok := a.(fmt.Stringer); ok {
fmt.Println(v.String())
}
英文:
As @volker mentioned; you cannot as the empty interface has no methods.
Please note: fmt.Sprint, fmt.Sprintf etc. does call Stringer interface first if its exists. It is elegant way.
Example of calling stringer interface after type assertion.
var a SomeType
if v, ok := a.(fmt.Stringer); ok {
fmt.Println(v.String())
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论