第九十天
发布者:admin 发表于:417天前 阅读数:501 评论:0

第九十天

1.下面代码能通过编译吗?

type T int

func F(t T) {}

func main() {
    var q int
    F(q)
}

2.下面代码能通过编译吗?请简要说明。

type T []int

func F(t T) {}

func main() {
    var q []int
    F(q)
}

我们将这两道题目放到一块做一个解析,第一题不能通过编译,第二题可以通过编译。我们知道不同类型的值是不能相互赋值的,即使底层类型一样,所以第一题编译不通过;对于底层类型相同的变量可以相互赋值还有一个重要的条件,即至少有一个不是有名类型(named type)。

这是 Go 语言规范手册的原文:

"x's type V and T have identical underlying types and at least one of V or T is not a named type. "

Named Type 有两类:

内置类型,比如 int, int64, float, string, bool 等;

使用关键字 type 声明的类型;

Unnamed Type 是基于已有的 Named Type 组合一起的类型,例如:struct{}、[]string、interface{}、map[string]bool 等。