Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Complex conditional statement in golang

I recently started learning golang and Revel. Im trying to understand what exactly the below if statement does. Seems like it is doing a type check, but i dont see what the conditional achieves. Appreciate if anyone can tell me whats happening here. thanks

if str, ok := obj.(string); ok {
return len(str) > 0
}
like image 900
broun Avatar asked Jan 11 '23 10:01

broun


1 Answers

It tries to convert obj (which is of some abstract interface probably) into a string, checks if that worked, and only enters if it turned out okay.

Written more sparsely it can be viewed as:

// do a type assertion/conversion of obj to a string. 
// If obj isn't really a string, ok will be false
str, ok := obj.(string) 

// this will only run if we're talking about a string
if ok {
 return len(str) > 0
}

What go does is safe casting from some interface to the real type. If you do this without the ok part, your program will panic if obj isn't a string. i.e this code will crash your program if obj isn't a string:

str := obj.(string) 
return len(str) > 0   

You can read more about type assertions in the docs:

http://golang.org/ref/spec#Type_assertions

like image 59
Not_a_Golfer Avatar answered Jan 21 '23 11:01

Not_a_Golfer