教程集 www.jiaochengji.com
教程集 >  Golang编程  >  golang教程  >  正文 Go 两种形式的“类型转换”

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

发布时间:2023-03-05   编辑:jiaochengji.com
教程集为您提供Go 两种形式的“类型转换”等资源,欢迎您收藏本站,我们将为您提供最新的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
到此这篇关于“Go 两种形式的“类型转换””的文章就介绍到这了,更多文章或继续浏览下面的相关文章,希望大家以后多多支持JQ教程网!

您可能感兴趣的文章:
php数组与Json转换的方法探讨
php数据类型转换学习笔记
Go的内存对齐和指针运算详解和实践
golang中类型比较和类型赋值说明
2.GO语言之基本数据类型,运算符
php数据类型的学习笔记
js读取并解析JSON类型数据
go语言int类型转化成string类型的方式
C#3.0 匿名类型介绍
应用编程基础课第三讲:Go编程基础

[关闭]
~ ~