首页 > 其他分享 >0079-Go-switch 分支

0079-Go-switch 分支

时间:2022-10-30 08:23:12浏览次数:66  
标签:Println case fmt Go switch time 0079 main

环境

  • Time 2022-08-23
  • Go 1.19

前言

说明

参考:https://gobyexample.com/switch

目标

使用 Go 语言的 switch 分支语句。

整数分支

package main

import "fmt"

func main() {

	i := 2
	fmt.Print("write ", i, " as ")
	switch i {
	case 1:
		fmt.Println("one")
	case 2:
		fmt.Println("two")
	case 3:
		fmt.Println("three")
	}
}

多个条件

package main

import (
	"fmt"
	"time"
)

func main() {

	switch time.Now().Weekday() {
	// 逗号分隔多个条件
	case time.Saturday, time.Sunday:
		fmt.Println("It's the weekend")
	default:
		fmt.Println("It's a weekday")
	}
}

表达式

package main

import (
	"fmt"
	"time"
)

func main() {

	t := time.Now()
	switch {
    // 可以接表达式,和 if/else 功能相同
	case t.Hour() < 12:
		fmt.Println("It's before noon")
	default:
		fmt.Println("It's after noon")
	}
}

类型选择

package main

import "fmt"

func main() {

	whatAmI(true)
	whatAmI(1)
	whatAmI("hey")
}

func whatAmI(a any) {
	// 类型选择 switch
	switch t := a.(type) {
	case bool:
		fmt.Println("I'm a bool")
	case int:
		fmt.Println("I'm an int")
	default:
		fmt.Printf("Don't know type %T\n", t)
	}
}

总结

使用 Go 语言的 switch 分支语句。

附录

标签:Println,case,fmt,Go,switch,time,0079,main
From: https://www.cnblogs.com/jiangbo4444/p/16840444.html

相关文章

  • 0080-Go-数组
    环境Time2022-08-23Go1.19前言说明参考:https://gobyexample.com/arrays目标使用Go语言的数组。申明数组packagemainimport"fmt"funcmain(){v......
  • 0081-Go-切片 slice
    环境Time2022-08-23Go1.19前言说明参考:https://gobyexample.com/slices目标使用Go语言的切片类型。新建切片类型packagemainimport"fmt"funcmain()......
  • 0082-Go-关联类型 map
    环境Time2022-08-23Go1.19前言说明参考:https://gobyexample.com/maps目标使用Go语言的关联类型map。新建mappackagemainimport"fmt"funcmain(){......
  • 0073-Go-hello world
    环境Time2022-08-23Go1.19前言说明参考:https://gobyexample.com/hello-world目标使用Go语言打印helloworld。初始化项目gomodinitjiangbo/go打印hel......
  • 0074-Go-值类型
    环境Time2022-08-23Go1.19前言说明参考:https://gobyexample.com/values目标使用Go语言的字符串,整型,浮点型和布尔类型。示例packagemainimport"fmt"fu......
  • Golang 基于 flag 库实现一个命令行工具
     Golang标准库中的flag库提供了解析命令行选项的能力,我们可以基于此来开发命令行工具。 假设我们想做一个命令行工具,我们通过参数提供【城市】,它自动能够返回当前......
  • 实验2:Open vSwitch虚拟交换机实践
    一、实验目的能够对OpenvSwitch进行基本操作;能够通过命令行终端使用OVS命令操作OpenvSwitch交换机,管理流表;能够通过Mininet的Python代码运行OVS命令,控制网络拓扑中的O......
  • golang中的锁竞争问题
    当我们打印错误的时候使用锁可能会带来意想不到的结果。我们看下面的例子:packagemainimport("fmt""sync")typeCoursewarestruct{mutexsync.RWMutexIdint6......
  • golang中的nil接收器
    我们先看一个简单的例子,我们自定义一个错误,用来把多个错误放在一起输出:typeCustomErrorstruct{errors[]string}func(c*CustomError)Add(errstring){c.errors=......
  • golang中的字符串
    0.1、索引​​https://waterflow.link/articles/1666449874974​​1、字符串编码在go中rune是一个unicode编码点。我们都知道UTF-8将字符编码为1-4个字节,比如我们常用的汉字......