前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >golang-101-hacks(22)——Types

golang-101-hacks(22)——Types

作者头像
羊羽shine
发布2019-07-01 18:14:36
4830
发布2019-07-01 18:14:36
举报
文章被收录于专栏:Golang开发

注:本文是对golang-101-hacks中文翻译

Go语言中的数据类型可分为两类:已命名和未命名。除了预先已声明的类型(如“int”、“rune”等),还可以自己定义命名类型。例如:

代码语言:javascript
复制
type mySlice []int

未命名类型由文字类型定义。即, []int是一个未命名的类型。 根据Go spec,每种类型都有一个底层类型: Unnamed types are defined by type literal. I.e., []int is an unnamed type. According to Go spec, there is an underlying type of every type: 每个类型T都有一个底层类型:如果T是预先声明的布尔型、数值型、字符串型或文字型中的一种,对应的底层类型就是T本身。否则,T的基础类型就是T在其类型声明中引用的类型的基础类型。

因此,在上面的示例中,命名类型“mySlice”和未命名类型“[]int”都具有相同的底层类型:“[]int”。 go有严格的变量赋值规则。例如:

代码语言:javascript
复制
package main

import "fmt"

type mySlice1 []int
type mySlice2 []int

func main() {
    var s1 mySlice1
    var s2 mySlice2 = s1

    fmt.Println(s1, s2)
}

编译会报错: The compilation will complain the following error:

代码语言:javascript
复制
cannot use s1 (type mySlice1) as type mySlice2 in assignment

虽然' s1 '和' s2 '的底层类型相同:' []int ',但是它们属于' 两 '种不同的命名类型(' mySlice1 '和' mySlice2 '),所以它们不能彼此赋值。但如果您将' s2 '的类型修改为' []int ',编译就没有问题: Although the underlying type of s1 and s2 are same: []int, but they belong to 2 different named types (mySlice1 and mySlice2), so they can't assign values each other. But if you modify s2's type to []int, the compilation will be OK:

代码语言:javascript
复制
package main

import "fmt"

type mySlice1 []int

func main() {
    var s1 mySlice1
    var s2 []int = s1

    fmt.Println(s1, s2)
}

它背后的神奇之处在于一条规则可转让性 x的类型V和T具有相同的底层类型,并且至少有一个V或T不是命名类型。 参考: Go spec; Learning Go - Types; Golang pop quiz.

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019.06.26 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档