Docker教程 · 2024年11月18日

GO中断言interface类型的方法

方法一:

if sw, ok := w.(stringWriter); ok {
   return sw.WriteString(s)
}

根据ok的值判断断言是否成功。

 

方法二:

switch a.(type) {
      case int64:
          if i, ok := a.(int64); ok {
              return int(i),nil
          }
      case float64:
          if i, ok := a.(float64); ok {
              return int(i),nil
          }
      default:
          return 0,errors.New("Don't change to Int")
  }

方法二一般用在需要断言类型比较多的情况。