7.2 Go type assertion

类型断言是使用在接口值上的操作。

语法x.(T)被称为类型断言,x代表接口的类型,T代表一个类型检查。

类型断言检查它操作对象的动态类型是否和断言类型匹配

类型断言快速入门

package main

import (
"fmt"
) type Point struct {
x int
y int
} func main() { var a interface{}
var point Point = Point{1, 2}
//任何类型都实现了空接口
a = point
fmt.Printf("类型:%T 值:%v\n", a, a) /*
想要将a赋值给b变量,可以直接这么玩吗?
var b Point
b = a
报错
cannot use a (type interface {}) as type Point in assignment: need type assertion
提示需要类型断言type assertion
*/
var b Point
b, ok := a.(Point)
if ok {
fmt.Printf("类型:%T 值:%v\n", b, b)
}
}

1.1. 类型断言介绍

在类型断言时,如果类型不匹配,程序会直接panic异常退出,因此要确保类型断言,空接口指向的就是断言的类型,或者加上检查机制,防止程序panic退出。

package main

import (
"fmt"
) //test函数接收一个空接口,可以接收任意的数据类型
func test(a interface{}) { //带有检查机制的类型断言,ok是布尔值,返回true或false
s, ok := a.(int)
if ok {
fmt.Println(s)
//手动return结束这个类型检查
return
} str, ok := a.(string)
if ok {
fmt.Println(str)
return
} f, ok := a.(float32)
if ok {
fmt.Println(f)
return
} fmt.Println("can not define the type of a")
} //测试test函数类型检查
func testInterface1() {
var a int = 100
test(a) var b string = "hello"
test(b)
} //使用分支判断,检测类型断言
func testSwitch(a interface{}) {
//直接switch跟着类型断言表达式
switch a.(type) {
case string:
fmt.Printf("a is string, value:%v\n", a.(string))
case int:
fmt.Printf("a is int, value:%v\n", a.(int))
case int32:
fmt.Printf("a is int, value:%v\n", a.(int))
default:
fmt.Println("not support type\n")
}
} func testSwitch2(a interface{}) {
//将类型断言结果赋值给变量
switch v := a.(type) {
case string:
fmt.Printf("a is string, value:%v\n", v)
case int:
fmt.Printf("a is int, value:%v\n", v)
case int32:
fmt.Printf("a is int, value:%v\n", v)
default:
fmt.Println("not support type\n")
}
} func testInterface2() {
var a int = 123456
testSwitch(a)
fmt.Println("-------------")
var b string = "hello"
testSwitch(b)
} func testInterface3() {
var a int = 100
testSwitch2(a)
var b string = "hello"
testSwitch2(b)
} func main() {
//testInterface1()
//testInterface2()
testInterface3()
}

7.2 Go type assertion的更多相关文章

  1. [golang] go的typeswitch guard(类型区别)语法和type assertion(类型断言)语法

    最近在实现golang,看到个go的特性语法: typeswitch guard. typeswitch guard语法如下: package main import "fmt" ...

  2. TypeScript & as & Type Assertion

    TypeScript & as & Type Assertion Type Assertion (as) That is not vanilla JavaScript, it is T ...

  3. Go 的类型断言type assertion

    Go语言中的类型断言,语法上是这样的: x.(T) 其中,x是interface接口的表达式,T是类型,称为被断言类型. 补充一下,接口有接口值的概念,其包括动态类型和动态值两部分. 类型断言根据T的 ...

  4. Go语言中cannot convert adminname (type interface {}) to type *: need type assertion的解决办法

    解决的办法是把string(adminname)替换为adminname.(string).其它类型也是类似.

  5. go 报 need type assertion

    responese_total := m["responses"].([]interface{})[0].(map[string]interface{})["hits&q ...

  6. [TypeScript] Work with DOM Elements in TypeScript using Type Assertions

    The DOM can be a bit tricky when it comes to typing. You never really know exactly what you're going ...

  7. (type interface {}) to type string

    go 语言开发中,经常会在函数中碰到使用 insterface{} 作为接收任意参数,但是我们接收的数据经常是需要做类型转换,由于是初学者,因此,初次转换我是直接就 func New(paramete ...

  8. [TypeScript] Type check JavaScript files using JSDoc and Typescript 2.5

    Typescript 2.5 adds JSDoc type assertion support for javascript file via ts-check service. First of ...

  9. [TypeScript] Using Assertion to Convert Types in TypeScript

    Sometimes the compiler needs help figuring out a type. In this lesson we learn how to help out the c ...

随机推荐

  1. MySql --FIND_IN_SET() 函数 (转)

    例子:https://www.jianshu.com/p/b2c1ba0ba34f 举个例子来说:有个文章表里面有个type字段,他存储的是文章类型,有 1头条,2推荐,3热点,4图文 .....11 ...

  2. linux抓包的实现

    工具: wireshark tcpdump 在这里仅仅介绍后者: 在网络问题的调试中,tcpdump应该说是一个必不可少的工具,和大部分linux下优秀工具一样,它的特点就是简单而强大. 默认情况下, ...

  3. 在Spring Boot中加载初始化数据

    文章目录 依赖条件 data.sql文件 schema.sql 文件 @sql注解 @SqlConfig 注解 在Spring Boot中加载初始化数据 在Spring Boot中,Spring Bo ...

  4. 【Linux题目】第四关

    1. 如何过滤出已知当前目录下oldboy中的所有一级目录? 提示:不包含oldboy目录下面目录的子目录和隐藏目录,只要一级目录即可. 解答: ls -F|grep /   通过ls -F给目录后面 ...

  5. windows服务程序的编写

    服务编写https://blog.csdn.net/lanuage/article/details/77937407 #include <windows.h> #include <s ...

  6. Mockjs+Ajax实践

    需要完成的工作:利用mock js随机生成数据,通过ajax请求,获取这些数据并展示在网页中. 一 mock js随机生成数据 官方文档中,Mock.mock( ),可以说是mock的精髓所在. Mo ...

  7. Linux利用udev提权

    友老催我写个webshell+udev localroot的文章.这周末有点空闲时间,捣鼓了一下.公开的udev exploit有两个.一个是kcope写的SHELL版本,一个是jon写的C版本. s ...

  8. jmeter正则表达式提取多个数据/一组数据时,应该怎么做——debug sampler的使用

    背景:今天有个接口需要借助前面接口产生的一组ids数据,来作为入参使用,但是之前都是提取单个接口,所以到底怎么提取接口,遇到了很大的问题,按照多方查取资料都没有成功,最终在一个不相关帖子的最后一句话被 ...

  9. VUE生命周期中的钩子函数及父子组件的执行顺序

    先附一张官网上的vue实例的生命周期图,每个Vue实例在被创建的时候都需要经过一系列的初始化过程,例如需要设置数据监听,编译模板,将实例挂载到DOM并在数据变化时更新DOM等.同时在这个过程中也会运行 ...

  10. kafka-eagle监控kafka

    最近想做一个kafka监控,本来准备用zabbix来监控的,需要重复造轮子,本来准备用kafka-Manager的,在GitHub上无意发现了kafka-eagle,看了官方介绍准备试一下..... ...