7.2 Go type assertion
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的更多相关文章
- [golang] go的typeswitch guard(类型区别)语法和type assertion(类型断言)语法
最近在实现golang,看到个go的特性语法: typeswitch guard. typeswitch guard语法如下: package main import "fmt" ...
- TypeScript & as & Type Assertion
TypeScript & as & Type Assertion Type Assertion (as) That is not vanilla JavaScript, it is T ...
- Go 的类型断言type assertion
Go语言中的类型断言,语法上是这样的: x.(T) 其中,x是interface接口的表达式,T是类型,称为被断言类型. 补充一下,接口有接口值的概念,其包括动态类型和动态值两部分. 类型断言根据T的 ...
- Go语言中cannot convert adminname (type interface {}) to type *: need type assertion的解决办法
解决的办法是把string(adminname)替换为adminname.(string).其它类型也是类似.
- go 报 need type assertion
responese_total := m["responses"].([]interface{})[0].(map[string]interface{})["hits&q ...
- [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 ...
- (type interface {}) to type string
go 语言开发中,经常会在函数中碰到使用 insterface{} 作为接收任意参数,但是我们接收的数据经常是需要做类型转换,由于是初学者,因此,初次转换我是直接就 func New(paramete ...
- [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 ...
- [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 ...
随机推荐
- 浅谈 PHP 与手机 APP 开发
来源:http://www.thinkphp.cn/topic/5023.html 一.先简单回答两个问题: 1.PHP 可以开发客户端?答:不可以,因为PHP是脚本语言,是负责完成 B/S架构 或 ...
- PHP实现MySQL并发查询
一般的,一个看似很简单的页面,一次http请求后,到达服务端,穿过Cache层,落到后台后,实际可能会有很多很多的数据查询逻辑!而这些查询实际是不相互依赖的,也即可以同时查询.比如各种用户信息,用户的 ...
- JDK 14的新特性:更加好用的NullPointerExceptions
JDK 14的新特性:更加好用的NullPointerExceptions 让99%的java程序员都头痛的异常就是NullPointerExceptions了.NullPointerExceptio ...
- SpringCloud入门(十一):Sleuth 与 Zipkin分布式链路跟踪
现今业界分布式服务跟踪的理论基础主要来自于 Google 的一篇论文<Dapper, a Large-Scale Distributed Systems Tracing Infrastructu ...
- Linux系统应用管理:增加普通用户(密码管理等)
1. 查看当前Linux系统的版本.内核等信息 [root@oldboy ~]# cat /etc/redhat-release CentOS release 6.7 (Final) . # 系统版本 ...
- 【Linux常见命令】diff命令
diff - compare files line by line diff命令用于比较文件的差异. diff以逐行的方式,比较文本文件的异同处. 如果指定要比较目录,则diff会比较目录中相同文件名 ...
- mac OS 安装配置Nginx服务器
系统环境 安装工具 Homebrew软件包管理器 :<mac OS 安装 Homebrew软件包管理器>https://blog.csdn.net/weixin_41791279/arti ...
- 解析HTML、JS与PHP之间的数据传输
在电商网站搭建过程中,前端经常会向后端请求数据,有时候通过HTML.JS和PHP文件的处理来实现数据的连通.通常情况下,用户在HTML中做关键字操作,JS对提交的表单进行数据处理,向后端发起ajax请 ...
- 源码阅读:Masonry(三)—— MASViewAttribute
该文章阅读的 Masonry 的版本为 1.1.0. 这个类我们可以叫它"约束视图及其属性类",它封装了设置约束的视图和其设置约束的属性,也就是 view1 和 attr1,或是 ...
- Taurus.MVC 2.3.2 :WebAPI 文档集成测试功能及附加<%# JS执行功能语法 %>
前言: 前些天有网友提到了那个界面丑陋的SwaggerUI,让我想起了多年前实现的WebAPI文档未完成的功能点,于是,动手了,便有了本文的内容. 开源地址:https://github.com/cy ...