【go语言学习】type关键字

type是go语法里的重要而且常用的关键字,type绝不只是对应于C/C++中的typedef。搞清楚type的使用,就容易理解go语言中的核心概念struct、interface、函数等的使用。

一、类型定义

1、定义结构体

使用type可以定义结构体

type Preson struct {
        name string
        age int
}
2、定义结构

使用type可以定义接口

type USB interface {
        start()
        end()
}
3、定义新的类型
type Type
4、函数类型

使用type定义函数类型

type fun func () int

二、类型别名

类型别名的写法为:

type 别名 = Type

类型别名规定:TypeAlias 只是 Type 的别名,本质上 TypeAlias 与 Type 是同一个类型。就像一个孩子小时候有小名、乳名,上学后用学名,英语老师又会给他起英文名,但这些名字都指的是他本人。

三、类型定义和类型别名的区别

package main

import "fmt"

type newInt int

type myInt = int

func main() {
    var a newInt = 10
    var b myInt = 10
    // fmt.Println(a == b) //invalid operation: a == b (mismatched types newInt and int)
    fmt.Printf("%T, %T\n", a, b) //main.newInt, int
}

a的类型是main.newInt, b的类型是int, myInt类型只在代码中存在,编译完成并不会有myInt类型。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。