Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 835
Daksh Miglani Avatar asked Dec 02 '18 06:12

Daksh Miglani


2 Answers

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.

like image 129
poy Avatar answered Nov 07 '22 17:11

poy


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

like image 41
nightfury1204 Avatar answered Nov 07 '22 16:11

nightfury1204