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")
  }

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

发表评论

电子邮件地址不会被公开。 必填项已用*标注

您可以使用这些HTML标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>