"i.(string)"是什么意思?在golang语法中实际上意味着什么? [英] What does "i.(string)" actually mean in golang syntax?

查看:237
本文介绍了"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.

这篇关于"i.(string)"是什么意思?在golang语法中实际上意味着什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆