golang 类型断言的学习
在php中有一个 serialize() 函数 可以把数组序列化成字符串进行存储和传输
如果想反序列化这种字符串,在php中只需要一个简单的unserialize() 函数就可以完成了.但是在golang中可就没有这么容易了,非得费个九牛二虎之力,写上不少代码才行。
这时候只想感叹一下,php真的是世界上最好的语言啊!
我就在今天的开发中遇到了这么个问题,需要使用golang去解析php序列化的字符串,在github上找了个解析的包,但是发现解析之后的结果是个interface{}类型。
顿时我就无从下手了,总在想数据实际上是一个map,但是解析后得到一个interface{} , 这让我怎么用啊
感觉需要用类型断言,但又不太会用,遂去社区问一下吧,期望大佬们能给个答案。
实际上确实很管用。
下面贴一下代码:
package main import (
"github.com/yvasiyarov/php_session_decoder/php_serialize"
"fmt"
"log"
) func main() {
// 序列化后的字符串
str := `a:3:{s:4:"name";s:3:"tom";s:3:"age";s:2:"23";s:7:"friends";a:2:{i:0;a:1:{s:4:"name";s:5:"jerry";}i:1;a:1:{s:4:"name";s:4:"jack";}}}` // 反序列化
decoder := php_serialize.NewUnSerializer(str)
if result, err := decoder.Decode(); err != nil {
panic(err)
} else {
// 此处进行类型断言
decodeData, ok := result.(php_serialize.PhpArray)
if !ok {
log.Println(err)
} // 断言后,即可获取内容
name := decodeData["name"]
age := decodeData["age"]
fmt.Println(name, age) // 内层数据仍需再次断言
friends, ok := decodeData["friends"].(php_serialize.PhpArray)
if !ok {
log.Println(err)
} // 断言成功后即可获取内部数据
for _,v := range friends {
fmt.Printf("type:%T, value:%+v\n", v,v )
friend, ok := v.(php_serialize.PhpArray)
if !ok {
log.Println(err)
}
friendName := friend["name"]
fmt.Println(friendName)
}
}
}
可以粗暴的这么理解:一个变量是什么类型,就进行什么类型的断言,断言后,即可得到结果
怎么判断一个变量的类型?
打印出来呀:fmt.Printf("%T", verb)
%T这个占位符可以显示变量的类型
下面还有个示例:
package main import (
"github.com/yvasiyarov/php_session_decoder/php_serialize"
"fmt"
"log"
) func main() {
// 序列化后的字符串
str := `a:3:{s:4:"name";s:3:"tom";s:3:"age";s:2:"23";s:7:"friends";a:2:{i:0;a:1:{s:4:"name";s:5:"jerry";}i:1;a:1:{s:4:"name";s:4:"jack";}}}` // 反序列化
decoder := php_serialize.NewUnSerializer(str)
result, err := decoder.Decode()
if err != nil {
panic(err)
}
// 类型断言
t := result.(php_serialize.PhpArray)
strVal := php_serialize.PhpValueString(t["name"])
fmt.Println(strVal) switch t := result.(type) {
default:
fmt.Printf("unexpected type %T\n", t)
case php_serialize.PhpArray:
fmt.Println(t)
fmt.Println(t["name"])
fmt.Println(t["age"]) switch f := t["friends"].(type) {
default:
fmt.Printf("unexpected type %T\n", t)
case php_serialize.PhpArray:
fmt.Println(f)
fmt.Println(f[0])
fmt.Println(f[1])
}
}
}
上面两个demo都可以达到效果,只是写法不同。
后面我又经人介绍,得到了另外一个包,也能达到效果:
package main import (
"fmt"
"log"
"github.com/wulijun/go-php-serialize/phpserialize"
) func main() {
str := `a:3:{s:4:"name";s:3:"tom";s:3:"age";s:2:"23";s:7:"friends";a:2:{i:0;a:1:{s:4:"name";s:5:"jerry";}i:1;a:1:{s:4:"name";s:4:"jack";}}}`
decodedRes, err := phpserialize.Decode(str)
if err != nil {
panic(err)
}
//fmt.Printf("%T\n", decodedRes) //type is map[interface{}]interface{} //type assert
decodedData, ok := decodedRes.(map[interface{}]interface{})
if !ok {
fmt.Printf("unexpected type %T\n", decodedRes)
}
fmt.Println(decodedData["name"])
fmt.Println(decodedData["age"]) //fmt.Printf("%T\n", decodedData["friends"]) // type is map[interface{}]interface{}
// type assert
friendsRes, ok := decodedData["friends"].(map[interface{}]interface{})
if !ok {
fmt.Printf("unexpected type %T\n", decodedData["friends"])
}
for _,v := range friendsRes {
//fmt.Printf("type: %T, val: %#v\n", v,v) // type is map[interface{}]interface{}
friend, ok := v.(map[interface{}]interface{})
if !ok {
fmt.Printf("unexpected type %T\n", decodedData["friends"])
}
//fmt.Printf("type: %T, val: %#v\n", friend,friend) // type is map[interface{}]interface{}
fmt.Println(friend["name"])
}
}
这个包解析出来的所有结果的类型都是map[interface{}]interface{},所以做类型断言的时候可以简单粗暴一些
下面是我在segmentfault和stackoverflow上面的提问,我上面的示例demo也是来源于问题中大佬们的回答,有兴趣可以看下:
segmentfault:https://segmentfault.com/q/1010000010690732
stackoverflow:https://stackoverflow.com/questions/45705930/how-to-get-values-from-a-interface-in-golang/
golang 类型断言的学习的更多相关文章
- golang类型断言
一.介绍 类型断言,由于接口是一般类型,不知道具体类型,如果要转成具体类型,就需要使用类型断言 例子: package main import "fmt" func main(){ ...
- [Go] golang类型断言
类型断言有点像向下转型,接口类型转到具体的实现实例类型上类型断言是一个使用在接口值上的操作.语法上它看起来像x.(T)被称为断言类型,这里x表示一个接口的类型和T表示一个类型 package main ...
- [Golang学习笔记] 06 程序实体3 类型断言和类型转换
类型断言: 语法:<目标类型的值>,<布尔参数> := <表达式>.( 目标类型 ) // 安全类型断言<目标类型的值> := <表达式>. ...
- golang学习笔记:Interface类型断言详情
原文链接:https://www.2cto.com/kf/201712/703563.html 1. 用于判断变量类型 demo如下: switch t := var.(type){ case str ...
- [golang] go的typeswitch guard(类型区别)语法和type assertion(类型断言)语法
最近在实现golang,看到个go的特性语法: typeswitch guard. typeswitch guard语法如下: package main import "fmt" ...
- Golang的类型断言
类型断言即判断一个变量是不是某个类型的实例,这个经常用在判断接口的类型,基本的格式: y, ok := x.(type) 上面的语句用于判断变量x是不是type类型,有两种结果: x是type类型的变 ...
- Golang之interface(多态,类型断言)
多态用法 package main //一种事物的多种形态,都可以按照统一的接口进行操作 //多态 import ( "fmt" "math/rand" &qu ...
- Go的类型断言解析
经常地我们对一个接口值的动态类型是不确定的,如方法的形参为接口类型时,此时就需要检验它是否符合我们需要的类型.类型断言是一个使用在接口值上的操作.断言类型的语法:x.(T),这里x表示一个接口的类型, ...
- Go语言的类型转换和类型断言
https://my.oschina.net/chai2010/blog/161418 https://studygolang.com/articles/9335 类型转换.类型断言和类型切换 ht ...
随机推荐
- C# 文件去仅仅读工具-线程-技术&分享
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; usin ...
- html5 canvas 画板
<!doctype html> <head> <meta http-equiv="Content-Type" content="text/h ...
- Python笔记·第七章—— IO(文件)处理
一.文件处理简介 计算机系统分为:计算机硬件,操作系统,应用程序三部分. 我们用python或其他语言编写的应用程序若想要把数据永久保存下来,必须要保存于硬盘中,这就涉及到应用程序要操作硬件,众所周知 ...
- WebGL学习(3) - 3D模型
原文地址:WebGL学习(3) - 3D模型 相信很多人是以创建逼真酷炫的三维效果为目标而学习webGL的吧,首先我就是
- 开源免费接口管理平台eoLinker AMS开源版 V3.2.0更新,增加批量导出导入接口功能!
eoLinker是一个免费开源的针对开发人员需求而设计的接口管理工具,通过简单的操作来帮助开发者进行接口文档管理.接口自动化测试.团队协作.数据获取.安全防御监控等功能,降低企业的接口管理成本,提高项 ...
- Android开发之常见事件响应方式
常见的事件有 (1)单击事件 onClickListener (2)长按事件 onLongClickListener (3)滑动事件 onTouchListener (4)键盘事件 onKeyLi ...
- 微信小程序教学第二章:小程序中级实战教程之预备篇 - 项目结构设计 |基于最新版1.0开发者工具
iKcamp官网:http://www.ikcamp.com 访问官网更快阅读全部免费分享课程:<iKcamp出品|全网最新|微信小程序|基于最新版1.0开发者工具之初中级培训教程分享>. ...
- 微信小程序基于最新版1.0开发者工具分享-小试牛刀(视频)+发布流程
第一章:小程序初级入门教程 小试牛刀[含视频] 视频地址:https://v.qq.com/x/page/i0554akzobq.html 这一章节中,我们尝试着写一个最简单的例子,包含 2 个静态页 ...
- /etc/services保存了服务、端口、协议
- SourceTree for Mac 破解版
soureTree For mac 破解版下载地址:链接: https://pan.baidu.com/s/1c19kFRi 密码: ai7f