分享
golang中的断言 形如 A.(T)
个00个 · · 3123 次点击 · · 开始浏览这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。
形如A.(T)
其中A只能为interface, T为类型, 可以是interface 或者其他类型. string, int, struct等.
- 若T为变量类型. 则用于判断转换为对应的变量类型. 这种用法可以使得一个函数接受多类型的变量.
func VarType(var interface {})(err error){
switch t := var.(type){
case string:
//add your operations
case int8:
//add your operations
case int16:
//add your operations
default:
return errors.New("no this type")
}
}
//空接口包含所有的类型,输入的参数均会被转换为空接口
//变量类型会被保存在t中
- 若T为interface, 则可以用用来判断A这个接口类型是否实现了特定接口.
package main
import (
"fmt"
"strconv"
)
type I interface{
Get() int
Put(int)
}
type P interface{
Print()
}
//定义结构体,实现接口I
type S struct {
i int
}
func (p *S) Get() int {
return p.i
}
func (p *S) Put(v int ) {
p.i = v
}
func (p *S) Print() {
fmt.Println("interface p:" + strconv.Itoa(p.i))
}
//使用类型断言
func GetInt( some interface {}) int {
if sp, ok := some.(P); ok { // 此处断言some这个接口后面隐藏的变量实现了接口P 从而调用了. P接口中的函数Print.
sp.Print()
}
return some.(I).Get()
}
func main(){
s := &S{i:5}
// a := GetInt(s)
fmt.Println(GetInt(s))
}
参考文章:
https://blog.csdn.net/Kiloveyousmile/article/details/78736718
就到这里咯.
有疑问加站长微信联系(非本文作者)
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
关注微信3123 次点击
添加一条新回复
(您需要 后才能回复 没有账号 ?)
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码` - 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传
收入到我管理的专栏 新建专栏
形如A.(T)
其中A只能为interface, T为类型, 可以是interface 或者其他类型. string, int, struct等.
- 若T为变量类型. 则用于判断转换为对应的变量类型. 这种用法可以使得一个函数接受多类型的变量.
func VarType(var interface {})(err error){
switch t := var.(type){
case string:
//add your operations
case int8:
//add your operations
case int16:
//add your operations
default:
return errors.New("no this type")
}
}
//空接口包含所有的类型,输入的参数均会被转换为空接口
//变量类型会被保存在t中
- 若T为interface, 则可以用用来判断A这个接口类型是否实现了特定接口.
package main
import (
"fmt"
"strconv"
)
type I interface{
Get() int
Put(int)
}
type P interface{
Print()
}
//定义结构体,实现接口I
type S struct {
i int
}
func (p *S) Get() int {
return p.i
}
func (p *S) Put(v int ) {
p.i = v
}
func (p *S) Print() {
fmt.Println("interface p:" + strconv.Itoa(p.i))
}
//使用类型断言
func GetInt( some interface {}) int {
if sp, ok := some.(P); ok { // 此处断言some这个接口后面隐藏的变量实现了接口P 从而调用了. P接口中的函数Print.
sp.Print()
}
return some.(I).Get()
}
func main(){
s := &S{i:5}
// a := GetInt(s)
fmt.Println(GetInt(s))
}
参考文章:
https://blog.csdn.net/Kiloveyousmile/article/details/78736718
就到这里咯.