gpt4 book ai didi

go - 为什么类型转换在编译时会失败?

转载 作者:行者123 更新时间:2023-12-01 22:35:16 25 4
gpt4 key购买 nike

考虑以下代码片段:

package main

import "fmt"

type Interface interface {
Fun()
}

type Int int

func (Int) Fun() {}

func main() {
var x interface{}
x = Int(42)
if _, ok := x.(int); !ok {
fmt.Println("type assertion fails")
}

// why do the lines below fail to compile?
var y Interface
y = Int(42)
if _, ok := y.(int); !ok {
fmt.Println("type assertion fails")
}
}

第一种断言按预期执行。但是,在第二种情况下,类型断言是在编译时执行的(换句话说,程序没有编译)

impossible type assertion: int does not implement Interface (missing Fun method)



我通过阅读“Go 编程语言”(第 206 页)的理解是,第二个片段应该编译,并且类型转换应该在运行时失败。

2个片段之间有什么区别吗?不都是xy接口(interface)类型(不同的接口(interface))?为什么第二个在编译时失败?

来自 C++ 背景,这看起来很像组合 static_assert (编译时间)和 assert (运行时)变成一个单一类型的断言,这看起来有点奇怪。

最佳答案

从规范:

More precisely, if T is not an interface type, x.(T) asserts that the dynamic type of x is identical to the type T. In this case, T must implement the (interface) type of x; otherwise the type assertion is invalid since it is not possible for x to store a value of type T. If T is an interface type, x.(T) asserts that the dynamic type of x implements the interface T.



https://golang.org/ref/spec#Type_assertions

所以预计它无法编译,因为 int不是接口(interface)类型;并且它没有实现 x ( Interface)。

关于go - 为什么类型转换在编译时会失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58652075/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com