"i.(string)"是什么意思?在golang语法中实际上意味着什么?

问题描述:

我最近开始寻找功能性的go示例,然后发现了此功能:

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"]

现在在此函数中,如您所见,映射器的return值为: strings.ToUpper(i.(string)).

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

但是,此i.(string)语法是什么意思?我尝试搜索,但没有发现任何特别有用的东西.

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

i.(string)强制转换(或至少尝试)i(类型interface{})以键入string.我说尝试是因为说iint,这会引起恐慌.如果这听起来不太好,那么您可以将语法更改为

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)

在这种情况下,如果i不是string,则ok将是false,并且代码不会惊慌.

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