go interface转换为int

文章发布于 2023-08-30

go语言是不支持接口类型数据转换为int类型数据的,因为接口是引用类型的数据。不过可以通过断言来实现类型的转换,但前提是知道具体的类型。

以下是接口类型数据转换int的简单实例:

package main
import "fmt"
type MyInterface interface {
    GetValue() int
}
type MyStruct struct {
    Value int
}
func (s MyStruct) GetValue() int {
    return s.Value
}

func main() {
    var myInterface MyInterface
    myStruct := MyStruct{Value: 42}
    myInterface = myStruct
    // 使用断言将接口类型转换为具体类型
    if concreteType, ok := myInterface.(MyStruct); ok {
        intValue := concreteType.GetValue()
        fmt.Println("Converted int:", intValue)
    } else {
        fmt.Println("Conversion failed")
    }
}

在上面的示例定义了一个接口 MyInterface或一个结构体 MyStruct。然后,将一个 MyStruct 实例赋值给 MyInterface 。接着使用类型断言 myInterface.(MyStruct) 来判断 myInterface 是否能被转换为 MyStruct 类型,如果可以,就可以通过具体类型访问其中的方法和字段。