golang接口和具体实现之间的类型转换

在 Go 语言中,如果你有一个接口类型的变量,并且你知道它的具体实现类型,你可以使用类型断言将其转换为具体类型。类型断言的语法是 value, ok := interfaceVar.(ConcreteType),其中 interfaceVar 是接口变量,ConcreteType 是具体类型。

复制代码
package main

import (
    "fmt"
)

// 定义一个接口
type Animal interface {
    Speak() string
}

// 定义一个具体类型
type Dog struct {
    Name string
}

// 实现接口方法
func (d Dog) Speak() string {
    return "Woof!"
}

func main() {
    // 创建一个 Dog 的实例,并将其赋值给接口类型的变量
    var animal Animal = Dog{Name: "Buddy"} 
    // case2:
    animalb := Animal(Dog{Name: "Buddy"})
    fmt.Printf("This animal is saying: %s\n", animalb.Speak())

    // 使用类型断言将接口变量转换为具体类型
    if dog, ok := animal.(Dog); ok {
        fmt.Printf("This is a Dog named %s and it says: %s\n", dog.Name, dog.Speak())
    } else {
        fmt.Println("The interface does not hold a Dog type")
    }

}
相关推荐
m0_748708054 分钟前
C++中的观察者模式实战
开发语言·c++·算法
qq_5375626716 分钟前
跨语言调用C++接口
开发语言·c++·算法
wjs202426 分钟前
DOM CDATA
开发语言
一点程序27 分钟前
基于SpringBoot的选课调查系统
java·spring boot·后端·选课调查系统
Tingjct28 分钟前
【初阶数据结构-二叉树】
c语言·开发语言·数据结构·算法
猷咪1 小时前
C++基础
开发语言·c++
IT·小灰灰1 小时前
30行PHP,利用硅基流动API,网页客服瞬间上线
开发语言·人工智能·aigc·php
快点好好学习吧1 小时前
phpize 依赖 php-config 获取 PHP 信息的庖丁解牛
android·开发语言·php
秦老师Q1 小时前
php入门教程(超详细,一篇就够了!!!)
开发语言·mysql·php·db
烟锁池塘柳01 小时前
解决Google Scholar “We‘re sorry... but your computer or network may be sending automated queries.”的问题
开发语言