Go语言之Switch语句怎么使用

发布时间:2022-06-30 09:49:19 作者:iii
来源:亿速云 阅读:134

这篇“Go语言之Switch语句怎么使用”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“Go语言之Switch语句怎么使用”文章吧。

基本语法

在讲述if-else时已经提到,如果有多个判断条件,Go语言中提供了Switch-Case的方式。如果switch后面不带条件相当于switch true

// Convert hexadecimal character to an int value
 switch {
 case '0' <= c && c <= '9':
     return c - '0'
 case 'a' <= c && c <= 'f':
     return c - 'a' + 10
 case 'A' <= c && c <= 'F':
     return c - 'A' + 10
 }
 return 0

fallthrough使用方法

默认情况下,case满足执行后会进行break,后面case即使满足条件也不再循环,如果想继续执行,则需要添加fallthrough,

package main

import "fmt"

func main() {
    i := 3
    switch i {
    case i > 0:
        fmt.Println("condition 1 triggered")
        fallthrough
    case i > 2:
        fmt.Println("condition 2 triggered")
        fallthrough
    default:
        fmt.Println("Default triggered")
    }
}

此时所有的case都会被执行

condition 1 triggered
condition 2 triggered
Default triggered

多条件匹配

如果同一个条件满足,也可以这样罗列到同一条件,相当于或条件

switch i {
    case 0, 1:
        f()
    default:
        g()
}

判断接口(interface)类型

空接口

后面我们会讲到接口,通过switch可以对type进行判断,获取接口的真实类型。

package main
  
import "fmt"
  
func main() {
    var value interface{}
    switch q:= value.(type) {
       case bool:
       fmt.Println("value is of boolean type")
       case float64:
       fmt.Println("value is of float64 type")
       case int:
       fmt.Println("value is of int type")
       default:
       fmt.Printf("value is of type: %T", q)
   }
}

在上面的例子中,我们定义了一个空接口

var value interface{}

同时使用switch来判断类型

switch q:= value.(type) {

由于空接口没有内容,所以类型为nil,触发了default

value is of type: <nil>

获取实际类型

我们对上面的例子进行改造,同时让空接口拥有实际的值,再来看看执行的效果

package main

import "fmt"

func valueType(i interface{}) {
    switch q:= i.(type) {
       case bool:
       fmt.Println("value is of boolean type")
       case float64:
       fmt.Println("value is of float64 type")
       case int:
       fmt.Println("value is of int type")
       default:
       fmt.Printf("value is of type: %T\n", q)

   }
}

func main() {
    person := make(map[string]interface{}, 0)

    person["name"] = "Alice"
    person["age"] = 21
    person["height"] = 167.64

    fmt.Printf("%+v\n", person)

    for _, value := range person {
        valueType(value)
    }
}

这里有几个还没有讲到的知识点:

最后通过循环将变量传给valueType函数,看看程序输出什么结果

map[age:21 height:167.64 name:Alice]
value is of type: string
value is of int type
value is of float64 type

以上就是关于“Go语言之Switch语句怎么使用”这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注亿速云行业资讯频道。

推荐阅读:
  1. go语言switch语句用法
  2. 十四、流程控制之switch语句

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

go语言 switch

上一篇:微信小程序怎么实现答题功能

下一篇:python opencv3机器学习之EM算法怎么使用

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》