zoukankan      html  css  js  c++  java
  • go中interface作为参数和switch里的type

    package main
    
    import (
    	"fmt"
    	"time"
    )
    
    
    func main()  {
    	i :=2
    	fmt.Println("Write", i ,"as")
    	switch i {
    	case 1:
    		fmt.Println("one")
    	case 2:
    		fmt.Println("two")
    	case 3:
    		fmt.Println("three")
    	}
    	switch time.Now().Weekday() {
    	case time.Saturday,time.Sunday:
    		fmt.Println("It's the weekend")
    	default:
    		fmt.Println("Its a weekday")
    
    	}
    	//理解是获取接口实例实际的类型指针,以此调用实例所有可调用的方法,包括接口方法及自有方法。
    	//需要注意的是该写法必须与switch case联合使用,case中列出实现该接口的类型。
        //interface{}是可以传任意参数的,i.(type)必须在switch语句里使用,如果需要在其他位置就要使用reflect.Typeof
    	whatAmI := func(i interface{}) {
    		switch t:=i.(type) {
    		case bool:
    			fmt.Println("bool")
    		case int:
    			fmt.Println("int")
    		default:
    			fmt.Printf("dont know type %T",t)
    		}
    	}
    	whatAmI((true))
    	whatAmI((1))
    	whatAmI("hey")
    }
    
    
    
  • 相关阅读:
    非常可乐
    Find The Multiple
    盲点集锦
    Fliptile
    Catch That Cow
    Dungeon Master
    hdoj 1045 Fire Net
    hdoj 1342 Lotto【dfs】
    zoj 2100 Seeding
    poj 3620 Avoid The Lakes【简单dfs】
  • 原文地址:https://www.cnblogs.com/c-x-a/p/11203103.html
Copyright © 2011-2022 走看看