Complex conditional statement in golang

huangapple go评论101阅读模式
英文:

Complex conditional statement in golang

问题

最近我开始学习Go语言和Revel框架。我试图理解下面的if语句到底是做什么的。看起来它在进行类型检查,但我不明白条件语句的作用是什么。如果有人能告诉我这里发生了什么,我将不胜感激。谢谢。

if str, ok := obj.(string); ok {
    return len(str) > 0
}

这段代码的作用是检查obj是否为字符串类型。如果是字符串类型,将其赋值给str变量,并且ok的值为true。然后,判断str的长度是否大于0,如果是,则返回true,否则返回false

英文:

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
}

答案1

得分: 6

它试图将 obj(可能是某个抽象接口的对象)转换为字符串,检查是否成功,并且只有在成功的情况下才进入 if 语句块。

更简洁地写,可以看作是:

// 将 obj 进行类型断言/转换为字符串
// 如果 obj 不是一个真正的字符串,ok 将为 false
str, ok := obj.(string)

// 只有当我们在处理一个字符串时才会执行这部分代码
if ok {
    return len(str) > 0
}

Go 语言所做的是将某个接口安全地转换为实际类型。如果没有使用 ok 部分,如果 obj 不是一个字符串,你的程序将会发生 panic。也就是说,如果 obj 不是一个字符串,以下代码将会导致程序崩溃:

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

你可以在文档中了解更多关于类型断言的内容:

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

英文:

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

答案2

得分: 3

这被称为类型断言。你的变量obj是一个interface{},换句话说,它的真实类型可以在不同的执行中改变。类型断言用于确定interface{}的真实类型。有两种方法可以做到这一点:

str = obj.(string)

这种方法是不安全的:如果obj不是一个string,程序将会发生恐慌。另一种方法是你在代码中使用的方法。如果obj不是一个stringok布尔值将为false

例如:

func f(v interface{}) {
    if _, ok := v.(string); ok {
        fmt.Println("v是一个字符串!")
    } else if _, ok := v.(float64); ok {
        fmt.Println("v是一个float64!")
    } else {
         fmt.Println("v是其他类型...")
    }
}
f(17.42) // "v是一个float64!"
f("foobar") // "v是一个字符串!"
f([]string{"hello", "world"}) // "v是其他类型..."
英文:

This is called a type assertion. Your variable obj is an interface{}, in other words, its real type can change from one execution to another. A type assertion is used to determine the real type of an interface{}. There are two ways to do so:

str = obj.(string)

This one is unsecure: if ever obj is not a string, the program will panic. The other one is the one you used in your code. If obj is not a string, the ok boolean will be false.

For instance:

func f(v interface{}) {
    if _, ok := v.(string); ok {
        fmt.Println("v is a string!")
    } else if _, ok := v.(float64); ok {
        fmt.Println("v is a float64!")
    } else {
         fmt.Println("v is something else...")
    }
}
f(17.42) // "v is a float64!"
f("foobar") // "v is a string!"
f([]string{"hello", "world"}) // "v is something else..."

huangapple
  • 本文由 发表于 2014年6月9日 04:08:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/24110330.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定