注册 登录

清河洛

go中的type关键字

qingheluo2023-05-22清河洛428
type是go语法里的重要而且常用的关键字,搞清楚type的使用,就容易理解go语言中的核心概念struct、interface、函数等的使用一、定义结构体type struct_name struct { item1 val_type item2 val_type } 二、定义接口type interface_name interface{ method1() method1() } 三、定义函数类型type func_name func (type1,type2,...)(type1,type2,...) 在go中,函数可以作为另一个函数的参数,也可以作...

type是go语法里的重要而且常用的关键字,搞清楚type的使用,就容易理解go语言中的核心概念struct、interface、函数等的使用

一、定义结构体

type struct_name struct {
   item1 val_type
   item2 val_type
}

二、定义接口

type interface_name interface{
    method1()
    method1()
}

三、定义函数类型

type func_name  func (type1,type2,...)(type1,type2,...)

在go中,函数可以作为另一个函数的参数,也可以作为返回值,如果没有定义函数类型那么书写和维护起来比较困难

func myfunc (func_arg func(int,int)(int)) func(int)(int){
    //somecodes
    return func(num int) int{
        //somecodes
        return int_val
    }
}
以上代码向表达的意思就是
    myfunc函数接受一个接受两个int参数返回一个int值的函数
    返回值为一个接受一个int参数返回一个int值的函数
    如果函数接受的参数和返回值比较复杂,那么编写和阅读起来就比较困难,也不利于后期维护

type arg_func func(int,int)(int)
type re_func func(int)(int)
func myfunc (arg arg_func) re_func{
    //somecodes
    return re_func_val
    }
}
这样编写就比较容易理解和维护了

定义函数类型在函数式编程中特别重要

四、根据现有类型定义新类型

type type_name Type
根据一个已有的类型定义一个新的类型
两个类型具有相同的特性,但两者是不同的类型
相当于把一个已有的类型定义代码重新编写了一份并命名为新的类型名称
主要用于某些情况下的代码兼容问题

type myint32 int32
var my32 myint32 = 32
var i32 int32 = 32
fmt.Println(my32 == i32)
    // 报错,mismatched types myint32 and int32

五、定义类型别名

type type_name = Type
给一个已有的类型添加一个别名,两个类型指向相同

type myint32 int32
var my32 myint32 = 32
var i32 int32 = 32
fmt.Println(my32 == i32) // 打印true

六、定义指针类型

type PersonPtr *Person

七、定义空类型

type Empty interface{}

八、定义常量类型

type Color string

const (
    Red   Color = "red"
    Green Color = "green"
    Blue  Color = "blue"
)

九、定义数组类型

type IntArray [5]int

十、定义切片类型

type IntSlice []int

十一、定义映射类型

type StringMap map[string]string

十二、定义通道类型

type IntChan chan int


网址导航