go version go1.11 windows/amd64

 

本文为阅读Go语言中文官网的规则说明书(https://golang.google.cn/ref/spec)而做的笔记,完整的介绍Go语言的 类型(Types)

官文的 类型 的 目录结构 如下(12项):

Types
  -Method sets
  -Boolean types
  -Numeric types
  -String types
  -Array types
  -Slice types
  -Struct types
  -Pointer types
  -Function types
  -Interface types
  -Map types
  -Channel types

 

其中一些类型自己是熟悉的,但Go语言中特有的类型就不那么清楚了,比如,Channel types,第一次见到这种类型,也是重难点;Method sets的概念也是第一次见,好像和Interface types有些关系,需dig清楚;而Interface types也可以Java中的概念不一样;

其它的,Slice types在Python有所耳闻,但在Go里面是一个专门的类型;Struct、Pointer types的概念在C/C++中见到过,没想到这里又出现了。

审查后发现,总共12项,其中6项需要花精时弄清楚才行。

 

下面分别介绍(添加了一个type (...),出现在官文Types一节的开始位置,也是重难点):

-type (...)

这部分还不是很清楚,官文强翻(译)如下:

Go预定义了一些类型名称,其它类型则需要type关键字来声明。组合类型——比如,数组、结构体、指针、函数、接口、分片、映射和通道类型等——可以使用类型常量构建。

每一个类型 T 都有一个 底层类型:...(后面内容还是看官文吧!)

 

官文给的示例:

type (
	A1 = string
	A2 = A1
)

type (
	B1 string
	B2 B1
	B3 []B1
	B4 B3
)

上面的string、A1、A2、B1、B2的 底层类型 是 string,[]B1、B3、B4的底层类型是[]B1(我以为是 []string)。

 

下面是自己的测试,结果表明,上面的语句就是 定义类型别名 使用的嘛!

package main 

import (
	"reflect"
	"fmt"
)

type (
	A1 = string
	A2 = A1
)

type (
	B1 string
	B2 B1
	B3 []B1
	B4 B3
)

func main() {
	var str1 A1 = "1234"
	var str2 A2 = "abcd"
	
	fmt.Println("----测试1----")
	fmt.Println(str1)
	fmt.Println(str2)
	fmt.Println()
	fmt.Println(typeof(str1))
	fmt.Println(typeof(str2))
	fmt.Println()
	fmt.Println(typeof2(str1))
	fmt.Println(typeof2(str2))
	
	fmt.Println("----测试2----")
	
	var str3 B1 = "haha"
	var str4 B2 = "heihei"
	var strs1 B3
	strs1 = append(strs1, "dad", "mom")
	var strs2 B4
	strs2 = append(strs2, "tom", "jerry")
	
	fmt.Println(str3)
	fmt.Println(str4)
	fmt.Println(strs1)
	fmt.Println(strs2)
	fmt.Println()
	fmt.Println(typeof(str3))
	fmt.Println(typeof(str4))
	fmt.Println(typeof(strs1))
	fmt.Println(typeof(strs2))
	fmt.Println()
	fmt.Println(typeof2(str3))
	fmt.Println(typeof2(str4))
	fmt.Println(typeof2(strs1))
	fmt.Println(typeof2(strs2))
	
}

// https://studygolang.com/articles/10524
func typeof(v interface{}) string {
	return fmt.Sprintf("%T", v)
}

func typeof2(v interface{}) string {
	return reflect.TypeOf(v).String()
}
type (...)测试

相关文章: