Go: Type Assert

func TypeAssert(items ...interface{}) {
  for i, v := range items {
    switch v.(type) {
    case bool:
      fmt.Printf("index: %d, type: %T, value: %v\n", i, v, v)
    case float32, float64:
      fmt.Printf("index: %d, type: %T, value: %v\n", i, v, v)
    case int8, int16, int32, int64, int: // rune==int32  Duplicate case rune
      fmt.Printf("index: %d, type: %T, value: %v\n", i, v, v)
    case uint8, uint16, uint32, uint64: // byte==uint8  Duplicate case byte
      fmt.Printf("index: %d, type: %T, value: %v\n", i, v, v)
    case string:
      fmt.Printf("index: %d, type: %T, value: %v\n", i, v, v)
    case nil:
      fmt.Printf("index: %d, type: %T, value: %v\n", i, v, v)
    default:
      fmt.Printf("index: %d, type: %T, value: %v\n", i, v, v)
    }
  }
}

 

  type Vale struct {
    Name string
    Age  int
  }
  
  var inter interface{} = vale
  vale1, ok := inter.(Vale)
  if ok {
    fmt.Println(vale1.Name, vale1.Age)
  }
  switch v := inter.(type) {
  case Vale:
    fmt.Println(v.Name, v.Age)
  }

 

posted @ 2022-05-19 23:02  ascertain  阅读(15)  评论(0编辑  收藏  举报