码迷,mamicode.com
首页 > 其他好文 > 详细

go ---switch语句

时间:2019-10-08 12:43:45      阅读:76      评论:0      收藏:0      [点我收藏+]

标签:imp   unsigned   bbb   UNC   package   string   aaa   ack   div   

package main

import (
	"fmt"
)

func main() {

	var ar = [...]string{"A", "B", "D", "E"}

	for _, content := range ar {
		switch content {
		case "A":
			fmt.Println("AAA")
		case "B", "C", "D":
			fmt.Println("BBB")
		default:
			fmt.Println("CCC")
		}

	}

}

  输出:

AAA

BBB

BBB

CCC

 使用fallthrough,来向下一个case语句转移流程控制权,

package main

import (
	"fmt"
)

func main() {

	var ar = [...]string{"A", "B", "D", "E"}

	for _, content := range ar {
		switch content {
		case "A":
			fallthrough
		case "B", "C", "D":
			fmt.Println("BBB")
		default:
			fmt.Println("CCC")
		}

	}

}

  输出:

BBB

BBB

BBB

CCC

 

类型switch语句:对类型进行判定,而不是值

package main

import (
	"fmt"
)

func main() {

	v := 11

	switch i := interface{}(v).(type) {

	case int, int8, int16, int32, int64:

		fmt.Printf("A signed integer: %v. the type is :%T\n", v, v)
		fmt.Printf("A signed integer: %v. the type is :%T\n", i, i)
	case uint, uint8, uint16, uint32, uint64:

		fmt.Printf("A unsigned integer: %v. the type is :%T\n", v, v)
		fmt.Printf("A unsigned integer: %v. the type is :%T\n", i, i)

	default:

		fmt.Println("Unknown!")

	}

}

  输出:

A signed integer: 11. the type is :int

A signed integer: 11. the type is :int

package main

import (
	"fmt"
)

func main() {

	var v interface{}
	v = "hi"

	switch v.(type) {
	case string:
		fmt.Printf("The string is %v \n", v.(string))

	case int, int8, int16, int32, int64:

		fmt.Printf("A signed integer: %v. the type is :%T\n", v, v)

	case uint, uint8, uint16, uint32, uint64:

		fmt.Printf("A unsigned integer: %v. the type is :%T\n", v, v)

	default:

		fmt.Println("Unknown!")

	}

}

  输出:

The string is hi 

 

go ---switch语句

标签:imp   unsigned   bbb   UNC   package   string   aaa   ack   div   

原文地址:https://www.cnblogs.com/saryli/p/11634472.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!