What does “i.(string)” actually mean in golang syntax? [duplicate]

自古美人都是妖i 提交于 2020-05-29 05:06:09

问题


I recently started looking for functional go examples and I found this function:

mapper := func (i interface{}) interface{} {
    return strings.ToUpper(i.(string))
}
Map(mapper, New(“milu”, “rantanplan”))
//[“MILU”, “RANTANPLAN”]

Now in this function, as you can see the return value of mapper is: strings.ToUpper(i.(string)).

But, what does this i.(string) syntax mean? I tried searching, but didn't find anything particularly useful.


回答1:


i.(string) casts (or attempts at least) i (type interface{}) to type string. I say attempts because say i is an int instead, this will panic. If that doesn't sound great to you, then you could change the syntax to

x, ok := i.(string)

In this case if i is not a string, then ok will be false and the code won't panic.




回答2:


i.(string) means converting i(interface{} type) to string type.



来源:https://stackoverflow.com/questions/53577949/what-does-i-string-actually-mean-in-golang-syntax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!