Go type assertions

简介: Go type assertions

前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到网站

格式:x.(T)

含义:断言 x 不是 nil 并且存储的是 T 类型的值

用途:

  1. 检查 x 是否为 nil
  2. 检查 x 能否转换为类型 T
  3. 转换 x 为类型 T

返回值:

t := x.(T),返回一个类型为 T 的值,如果 xnil,产生 panic

t, ok := x.(T) ,如果 xnil 或者不是 T 类型,ok 的值为 false,否则 ok 的值为 true 并且 t 是一个类型为 T 的值。

使用方式:

v, ok = x.(T)
v, ok := x.(T)
var v, ok = x.(T)
var v, ok T1 = x.(T)

实际用途

  1. 判断 interface{} 的类型
  2. 转换 interface{} 为具体的类型
package main
import "fmt"
type Student struct {
  Name string
}
func test(i interface{}) interface{} {
  return i
}
func main() {
  var i interface{}
  student := Student{Name: "golang"}
  i = test(student)
  //fmt.Println(i.Name)  // i.Name undefined (type interface {} is interface with no methods)
  fmt.Println(i.(Student).Name) // 我们知道具体类型
  // 如果不知道具体类型,可以按照下面的方式判断
    // ok 为 true 说明 i 是 Student 类型,否则不是 Student 类型
  if j, ok := i.(Student); ok {
    fmt.Println(j.Name)
  }
    // 下面的 ok 为 false
    var ii interface{}
    ii = test(ii)
    if v, ok := ii.(Student); ok {
        fmt.Println(v.Name)
    } else {
        fmt.Println("ii is not Student")
    }
}

输出

golang
golang
ii is not Student


目录
相关文章
|
Go 索引
internal\model\data_support.go:17:10: cannot use _ as value or type
internal\model\data_support.go:17:10: cannot use _ as value or type
../../..xxx.go:46:18: aa.Bbb undefined (type *"xx/xxx/xx".Ccc has no field or method Bbb)
../../..xxx.go:46:18: aa.Bbb undefined (type *"xx/xxx/xx".Ccc has no field or method Bbb)
|
Go
Go语言type关键字终于被玩明白了 类型别名的秘密都在这里
Go语言type关键字终于被玩明白了 类型别名的秘密都在这里
551 0
|
Cloud Native 编译器 Go
100天精通Golang(基础入门篇)——第22天:深入探讨Go中的‘type‘关键字
100天精通Golang(基础入门篇)——第22天:深入探讨Go中的‘type‘关键字
218 0
|
JSON Go 数据格式
三分钟学 Go 语言——条件语句+switch和type switch
三分钟学 Go 语言——条件语句+switch和type switch
三分钟学 Go 语言——条件语句+switch和type switch
|
自然语言处理 Java 编译器
Go REFLECT Library | 01 - 反射的类型 Type
Go REFLECT Library | 01 - 反射的类型 Type
Go REFLECT Library | 01 - 反射的类型 Type
|
Go 索引
Go REFLECT Library | 02 - 反射的类型 Type
Go REFLECT Library | 02 - 反射的类型 Type
|
Go Windows
go的Type switch是一个switch语句么?
相信这样的语句在go中大家见的很多 switch t := arg.(type) { default: fmt.Printf("unexpected type %T\n", t) // %T prints whatever type t has case bool: fmt.
1046 0
|
3月前
|
存储 安全 Java
【Golang】(4)Go里面的指针如何?函数与方法怎么不一样?带你了解Go不同于其他高级语言的语法
结构体可以存储一组不同类型的数据,是一种符合类型。Go抛弃了类与继承,同时也抛弃了构造方法,刻意弱化了面向对象的功能,Go并非是一个传统OOP的语言,但是Go依旧有着OOP的影子,通过结构体和方法也可以模拟出一个类。
243 1
|
5月前
|
Cloud Native 安全 Java
Go:为云原生而生的高效语言
Go:为云原生而生的高效语言
328 1