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. Inno Setup, Pascal 字符串带双引号如何写

    Windows 的路径中如果有空格,就需要用双引号括起来.只能填 ASCII-Code-Number (decimal),不能用一般的 escape 方法. # + path + # 查询这个表的第一 ...

  2. React Native 在 Airbnb 的起起落落

    写在前面 Airbnb 早在 2016 年就上了 React Native 大船,是很具代表性的先驱布道者: In 2016, we took a big bet on React Native. T ...

  3. http 之 CORS简介

    什么是CORS? CORS:跨域资源共享.是一种机制. 用处? 它使用额外的 HTTP 头来告诉浏览器  让运行在一个 origin (domain) 上的Web应用被准许访问来自不同源服务器上的指定 ...

  4. 1309:【例1.6】回文数(Noip1999)

    传送门:http://ybt.ssoier.cn:8088/problem_show.php?pid=1309 [题目描述] 若一个数(首位不为零)从左向右读与从右向左读都是一样,我们就将其称之为回文 ...

  5. 前端跨域解决方案: JSONP的通俗解说和实践

     对于前端开发者而言,跨域是一个绕不开的话题.只有真正明白了各种方案的工作机制,才能针对性地进行跨域方案选型.本文将以探索者的视角,试图用最通俗的语言对一种"鼎鼎大名"的跨域解决方 ...

  6. winform练习-通过遍历Control容器中的对象统一委托事件-楼盘选择器

    1.窗体布局如下,一个label标签内容如下,一个btnSave按钮,用于保存,其他九个按钮用于选择楼盘. 2. 按钮存于Control容器中,编写方法遍历容器中的button,通过条件过滤掉不是bu ...

  7. C++条件分支结构

    一.对于近期学习知识点的摘要: 1. 从第一个.cpp文件谈起, #include<iostream> //头文件 using namespace std; //使用命名空间,namesp ...

  8. JS中由闭包引发内存泄露的深思

    目录 一个存在内存泄露的闭包实例 什么是内存泄露 JS的垃圾回收机制 什么是闭包 什么原因导致了内存泄露 参考 1.一个存在内存泄露的闭包实例 var theThing = null; var rep ...

  9. rabbitmq添加自启动 centos7环境

    1.编辑一个启动脚本 [root@xxx ~]# vim /usr/local/rabbitmq/sbin/start_rabbitmq.sh 内容如下(根据自己的实际位置做替换即可) #!/bin/ ...

  10. 内存迟迟下不去,可能你就差一个GC.Collect

    一:背景 1. 讲故事 我们有一家top级的淘品牌店铺,为了后续的加速计算,在程序启动的时候灌入她家的核心数据到内存中,灌入完成后内存高达100G,虽然云上的机器内存有256G,然被这么划掉一半看着还 ...