Go 两种形式的“类型转换”

Go 的类型转换常常让人有点迷,有两种形式的"类型转换":

  • Type(obj) :这种形式的类型转换要求 obj 对象的类型和 Type 是等价类型,即实现了相同的方法
  • obj.(Type) :这种形式用于向下转型,即接口对象转结构体对象,所以 obj 必须是一个接口对象 , 这种形式在 Go 中一般叫做类型断言

代码示例:

package main

import "fmt"

type Animal interface {
	GetName() string
}

// Cat 实现 Animal 接口
type Cat struct {
	name string
}
func (c *Cat)GetName() string {
	return "I'm cat : " + c.name
}

// Dog 实现 Animal 接口
type Dog struct {
	name string
}
func (d *Dog)GetName() string {
	return "I'm dog : " + d.name
}


func main() {
	cat := Cat{
		name: "hello kitty",
	}

	animal := Animal(&cat) // 结构体转接口,括号里需要传递一个 *Cat 类型而不能是 Cat 类型,因为是 *Cat 类型实现了 GetName() 方法,而不是 Cat 类型
	fmt.Println(animal.GetName())

	dog1 := Dog(cat) // 结构体之间进行转换,括号里需要传递一个 Cat 类型,因为 Cat = Dog, *Cat = *Dog
	fmt.Println(dog1.GetName())

	dog2 := (*Dog)(&cat)
	fmt.Println(dog2.GetName())  // 如上所述,*Cat = *Dog

	cat2, ok := animal.(*Cat) // 类型断言,左边必须是一个接口类型的对象,当接口对象的实际类型和要转换的目标类型匹配时,转换成功,否则失败
	if ok {
		fmt.Println("convert animal to cat - " + cat2.GetName())
	} else {
		fmt.Println("can not convert animal to cat")
	}

	dog3 , ok := animal.(*Dog) // 类型断言,接口对象的实际类型和要转换的目标类型不匹配
	if ok {
		fmt.Println("convert animal to dog - " + dog3.GetName())
	} else {
		fmt.Println("can not convert animal to dog")
	}

}

运行结果:

I'm cat : hello kitty
I'm dog : hello kitty
I'm dog : hello kitty
convert animal to cat - I'm cat : hello kitty
can not convert animal to dog
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值