Go-动态类型与类型断言详解(含type-switch及全部代码)

本文介绍了Go语言中如何处理动态类型,通过接口作为函数参数实现兼容多种类型。同时,讲解了类型断言和type-switch的使用,展示了如何判断变量的类型并进行不同操作。示例代码包括结构体、接口实现以及类型断言的实践应用。
摘要由CSDN通过智能技术生成

目录

动态类型

类型断言与type-switch

全部代码

截图

参考


动态类型

我们知道Go不像Python,变量可以没有类型。那么如果一个函数的参数需要兼容多个类型或是需要判断变量类型该如何做呢?

我们可以使用接口,上一篇文章Go-接口类型详解(定义、实现、接口继承比较等)介绍了接口及接口的使用,知道了接口变量可以接收实现了它的类型的变量。我们就可以用接口做参数。

结构体、接口与实现代码

type Cat struct {
	Name string
}

type Mouse struct {
	Name string
}

type Introduce interface {
	Intro()
}

func (c *Cat)Intro(){
	fmt.Println("hi, i am Cat, you can call me:",c.Name)
}

func (m *Mouse)Intro() {
	fmt.Println("hi, i am Mouse, you can call me:",m.Name)
}

接口参数

func selfIntro(in Introduce)  {
	in.Intro()
}

使用

	tom := Cat{"Tom"}
	selfIntro(&tom)
	jerry := Mouse{"Jerry"}
	selfIntro(&jerry)

类型断言与type-switch

go中有以下语法来对变量类型判断

value, ok = element.(T)

  • value 变量的值
  • ok是一个bool类型
  • element是interface变量
  • T是断言的类型

如果element存储了T类型的数值,那么ok就是true,否则就是false

type-switch

func typeJudge(x interface{})  {
	switch x.(type){
	case int,int8,int64,int16,int32,uint,uint8,uint16,uint32,uint64:
		fmt.Println("整型变量")
	case float32,float64:
		fmt.Println("浮点型变量")
	case []byte,[]rune,string:
		fmt.Println("字符串变量")
	default:
		fmt.Println("不清楚...")
	}
}

使用

	typeJudge(1)
	typeJudge(1.1)
	typeJudge("1.1")
	typeJudge([]byte("hi"))
	typeJudge([]int{1,2})

全部代码

package main

import "fmt"

type Cat struct {
	Name string
}

type Mouse struct {
	Name string
}

type Introduce interface {
	Intro()
}

func (c *Cat)Intro(){
	fmt.Println("hi, i am Cat, you can call me:",c.Name)
}

func (m *Mouse)Intro() {
	fmt.Println("hi, i am Mouse, you can call me:",m.Name)
}

func selfIntro(in Introduce)  {
	in.Intro()
}

func typeJudge(x interface{})  {
	switch x.(type){
	case int,int8,int64,int16,int32,uint,uint8,uint16,uint32,uint64:
		fmt.Println("整型变量")
	case float32,float64:
		fmt.Println("浮点型变量")
	case []byte,[]rune,string:
		fmt.Println("字符串变量")
	default:
		fmt.Println("不清楚...")
	}
}


func main() {
	//-----------动态类型--------------
	tom := Cat{"Tom"}
	selfIntro(&tom)
	jerry := Mouse{"Jerry"}
	selfIntro(&jerry)
	//-----------类型断言与type-switch--------
	typeJudge(1)
	typeJudge(1.1)
	typeJudge("1.1")
	typeJudge([]byte("hi"))
	typeJudge([]int{1,2})
}

截图

参考

Golang中的类型和类型断言

更多Go相关内容:Go-Golang学习总结笔记

有问题请下方评论,转载请注明出处,并附有原文链接,谢谢!如有侵权,请及时联系。如果您感觉有所收获,自愿打赏,可选择支付宝18833895206(小于),您的支持是我不断更新的动力。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lady_killer9

感谢您的打赏,我会加倍努力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值