2022-11-25 612
Go的switch的基本功能和C、Java类似:
特点:
switch 默认情况下 case 最后自带 break 语句,匹配成功后就不会执行其他 case
重点介绍Go当中的Switch的两个特别点:**
表达式判断为true还需要执行后面的 case,可以使用 fallthrough
type-switch 来判断某个 interface 变量中实际存储的变量类型
特点:
强制执行后面的 case 语句,fallthrough 不会判断下一条 case 的表达式结果是否为 true。
示例:
package main
import "fmt"
func main() {
    switch {
    case true:
        fmt.Println("1、case条件语句为false!")
        fallthrough
    case false:
        fmt.Println("2、case条件语句为true!")
    default:
        fmt.Println("默认的case")
    }
} 
代码分析:
特点:
语法格式:
switch x.(type){
    case type:
       statement(s);      
    case type:
       statement(s); 
    /* 你可以定义任意个数的case */
    default: /* 可选 */
       statement(s);
} 
示例:
package main
import (
    "fmt"
    "go/types"
)
func main() {
    var inter interface{} = true
    //使用变量去代替接口当中的值并且判断类型
    switch i := inter.(type) {
    case types.Nil:
        fmt.Println("x的类型是:", i)
    case int:
        fmt.Println("x是int类型")
    case float64:
        fmt.Println("x是float64类型")
    case func(int2 int):
        fmt.Println("x是func(int)类型")
    case bool, string:
        fmt.Println("x是bool或string类型")
    default:
        fmt.Println("未知类型")
    } 
可以直接判断接口当中的数据的数据类型
到此这篇关于Go中的条件语句Switch详解的文章就介绍到这了,更多相关Go条件语句Switch内容请搜索M135模板网以前的文章或继续浏览下面的相关文章希望大家以后多多支持M135模板网!
原文链接:https://www.tuonang.com/?id=2208
=========================================
https://www.tuonang.com/ 为 “模板狼-专注于苹果cms模板网站” 唯一官方服务平台,请勿相信其他任何渠道。
苹果cms模板 2022-09-09
苹果cms模板 2022-09-09
苹果cms模板 2022-09-09
苹果cms模板 2022-08-15
苹果cms模板 2022-09-09
苹果cms模板 2023-11-19
苹果cms模板 2023-11-18
苹果cms模板 2023-11-18
苹果cms模板 2022-09-09
苹果cms模板 2022-09-09
游客 2025年03月16日
游客 2025年03月16日
游客 2025年03月16日
游客 2025年03月16日
游客 2025年03月16日
扫码二维码
获取最新动态
