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. str_pad 和 filter_var

    这两个函数都是php内置函数,filter_var可直接过滤,比如邮箱,ip等,str_pad可补充字符串eg: 1  =>  001

  2. 设计可靠的udp

    推荐链接: https://www.cnblogs.com/lixiang-share/p/7152870.html

  3. Linux系统应用管理:增加普通用户(密码管理等)

    1. 查看当前Linux系统的版本.内核等信息 [root@oldboy ~]# cat /etc/redhat-release CentOS release 6.7 (Final) . # 系统版本 ...

  4. MyBatis学习总结(9)——使用MyBatis Generator自动创建代码

    2019独角兽企业重金招聘Python工程师标准>>> 由于MyBatis属于一种半自动的ORM框架,所以主要的工作就是配置Mapping映射文件,但是由于手写映射文件很容易出错,所 ...

  5. 截取nginx日志

    截取nginx日志 sed -n '/24\/Feb\/2017:11:00:00/,/24\/Feb\/2017:12:00:00/p' yunying_api.wanglibao.com.acce ...

  6. MaxCompute Studio提升UDF和MapReduce开发体验

    原文链接:http://click.aliyun.com/m/13990/ UDF全称User Defined Function,即用户自定义函数.MaxCompute提供了很多内建函数来满足用户的计 ...

  7. Pig设计模式概要以及与SQL的设计模式的对比

    2019独角兽企业重金招聘Python工程师标准>>> 1概要模式 概要模式其实就是数据的全貌信息的获取,主要分为3种: 1.1数值概要 #HSQL SELECT MIN(num), ...

  8. codeforce 270C Magical Boxes

    C. Magical Boxes Emuskald is a well-known illusionist. One of his trademark tricks involves a set of ...

  9. P1495 CRT,P4777 EXCRT

    updata on 2020.4.11 修正了 excrt 的一处笔误 CRT 求解方程: \[\begin{cases} x \equiv a_1 \pmod {m_1}\\ x \equiv a_ ...

  10. 蓝色展开收缩悬浮QQ客服代码

    放在我的博客首页上的的预览图: 在文章区的预览图如下: 代码如下: <div class="scrollsidebar" id="scrollsidebar&quo ...