golang-101-hacks(19)——switch

栏目: Go · 发布时间: 6年前

内容简介:注:本文是对和其他编程语言(例如C)相比,Go语音的Compared to other programming languages (such as C), Go's switch-case statement doesn't need explicit "break", and not have fall-though characteristic. Take the following code as an example:

注:本文是对 golang-101-hacks 中文翻译。

和其他编程语言(例如C)相比,Go语音的 switch-case 语句不需要显式的添加“break”,也没有 fall-though 。如下面代码所示:

Compared to other programming languages (such as C), Go's switch-case statement doesn't need explicit "break", and not have fall-though characteristic. Take the following code as an example:

package main

import (
    "fmt"
)

func checkSwitch(val int) {
    switch val {
    case 0:
    case 1:
        fmt.Println("The value is: ", val)
    }
}
func main() {
    checkSwitch(0)
    checkSwitch(1)
}

输出结果是

The value is:  1

期望当val为0或1时,执行 fmt.Println("The value is: ", val) ,但实际上,该语句只在val为1时生效。为了得到期望结果,有两种方法:

使用fallthrough:

func checkSwitch(val int) {
    switch val {
    case 0:
        fallthrough
    case 1:
        fmt.Println("The value is: ", val)
    }
}

(2)将0和1放在同一个的case语句下:

func checkSwitch(val int) {
    switch val {
    case 0, 1:
        fmt.Println("The value is: ", val)
    }
}

与if-else相比,switch语句表达判断更清晰和简单:

package main

import (
    "fmt"
)

func checkSwitch(val int) {
    switch {
    case val < 0:
        fmt.Println("The value is less than zero.")
    case val == 0:
        fmt.Println("The value is qual to zero.")
    case val > 0:
        fmt.Println("The value is more than zero.")
    }
}
func main() {
    checkSwitch(-1)
    checkSwitch(0)
    checkSwitch(1)
}

输出结果

The value is less than zero.
The value is qual to zero.
The value is more than zero.

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

删除

删除

[英] 维克托•迈尔-舍恩伯格(Viktor Mayer-Schönberger)著 / 袁杰 译 / 浙江人民出版社 / 2013-1 / 49.90元

《删除》讲述了遗忘的美德,为读者展现了大数据时代的取舍之道。 《删除》从大数据时代信息取舍的目的和方法分别诠释了“被遗忘的权利”。维克托首先回溯了人类追寻记忆的过程,之后提出数字技术与全球网络正在瓦解我们天生的遗忘能力。对此,他考察了促进遗忘终止4大驱动力——数字化,廉价的存储器,易于提取,全球性访问。之后,他提出了当前数字化记忆的两大威胁——信息权力与时间,并给出了应对威胁的6大对策——数......一起来看看 《删除》 这本书的介绍吧!

URL 编码/解码
URL 编码/解码

URL 编码/解码

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具