Golang基础——数据类型:接口

接口

type Tea struct {
	name string
	age  int
}
type Stu struct {
	Tea   // 匿名字段,为Tea类型,继承了Tea
	score int
}

func (s Stu) jiao() { // 值传递
	s.score = 11111
	fmt.Println(s.score)
}

func (s *Stu) jiao2() { // 指针传递
	s.score = 22222
	fmt.Println(s.score)
}

type ser interface { // 接口:规定要实现的方法,对象必须实现了规定的方法,才能赋值给接口
	jiao()
	jiao2() // 指针类型方法,要把对象地址赋值给接口
}

func main() {
	s := Stu{Tea{"aaa", 11}, 100}
	var ser1 ser
	ser1 = &s
	fmt.Println(ser1)
}

多态

type Tea struct {
	name string
	age  int
}
type Stu struct {
	Tea   // 匿名字段,为Tea类型,继承了Tea
	score int
}

func (s *Stu) jiao2() { // 指针传递
	fmt.Println("sjiao2")
}
func (t *Tea) jiao2() {
	fmt.Println("tjiao2")
}

type ser interface {
	jiao2()
}

func sayhello(s ser) {
	s.jiao2()
}

func (t Tea) jiao() int {
	return 1
}

type ser2 interface { // 子集
	// jiao() // jioa 有返回值,这样不行
	jiao() int // jiao的类型为:jiao() int
}

func (t Tea) sing() {
	fmt.Println("sing")
}

type ser3 interface { // 超集
	ser2
	sing()
}

func main() {
    // 同种调用方式,用于不同的对象,实现多态
	s := Stu{Tea{"aaa", 11}, 100}
	t := Tea{"bbb", 22}
	sayhello(&s)
	sayhello(&t)
}

接口之间的赋值:超集与子集

type Tea struct {
	name string
	age  int
}
type Stu struct {
	Tea   // 匿名字段,为Tea类型,继承了Tea
	score int
}

func (s *Stu) jiao2() { // 指针传递
	fmt.Println("sjiao2")
}
func (t *Tea) jiao2() {
	fmt.Println("tjiao2")
}

type ser interface {
	jiao2()
}

func sayhello(s ser) {
	s.jiao2()
}

func (t Tea) jiao() int {
	return 1
}

type ser2 interface { // 子集
	// jiao() // jioa 有返回值,这样不行
	jiao() int // jiao的类型为:jiao() int
}

func (t Tea) sing() {
	fmt.Println("sing")
}

type ser3 interface { // 超集
	ser2
	sing()
}

func main() {
    // 子集包含于超集,所以,子集不能赋值给超集
    // 因为子集方法少,不包含超集中的其他方法,所以,不能赋值给超集
    // 超集方法包含所有的子集方法,故能赋值给子集
	t2 := Tea{"ccc", 33}
	var sinter ser2
	sinter = t2
	fmt.Println(sinter)
	var sinter2 ser3
	sinter2 = t2
	fmt.Println(sinter2)
	sinter = sinter2
	// sinter2 = sinter  // 不行
}

空接口:可以接收任意类型的值

func main() {
	var c interface{} // 空接口可以接受任意类型的数据
	c = 111
	fmt.Println(c)
}

判断一个变量的类型:类型断言和switch测试

	// 类型断言
	var i interface{}
	i = 10
	v, ok := i.(int)
	fmt.Println(v, ok) // 10 true
	// 紧接着运行下一行报错:运行了之前的代码:v 已经是整型了,所以报错
	// v, ok = i.(string)  // cannot assign string to v (type int) in multiple assignment
	k, ok := i.(string)
	fmt.Println(k, ok) // 空字符串 false

	// switch测试
	var l []interface{}
	l = append(l, 1, "aaa", 'c')
	for _, v := range l {
		switch value := v.(type) {
		case int:
			fmt.Println("int", value)
		case string:
			fmt.Println("string", value)
		default:
			fmt.Println("不匹配", value)
		}
		// var kk interface{}
		// fmt.Println(kk.(type))  // use of .(type) outside type switch
	}
posted @   pythoner_wl  阅读(116)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示