go语言基础关键字type

利用type做别名测试

package main
import (
  "fmt"
  "time"
)

//语法 type TypeAlias = Type
//将NewInt定义为int类型,将 NewInt 定义为 int 类型,通过type关键字的定义则NewInt会形成一种新的类型
//注意NewInt本身依然具备int类型的特性,我们在很多地方都会自己定义这种

type NewInt int

//定义类型别名的写法为 type TypeAlias = Type
//将int取一个别名叫IntAlias,将 IntAlias 设置为 int 的一个别名,使用 IntAlias 与 int 等效。
type IntAlias = int

//为函数类型起别名
type f func (i int)
type externalf = f //(在包外就要用 type externalf f 形式)

/**********************************************************************************************
* 定义time.Duration的别名为MyDuration
* type MyDuration= time.Duration
* 编译则提示 cannot define new methods on non-local type time.Duration
* 非本地类型指的就是 time.Duration 不是在 main 包中定义的,而是在 time 包中定义的,与 main 包不在同一个包中,因此不能为不在一个包中的类型定义方法。
* ***/
// 修改为 type MyDuration time.Duration,也就是将 MyDuration 从别名改为类型
type MyDuration time.Duration
// 为MyDuration添加一个函数
func (m MyDuration) EasySet(a string) {
}

 

func main() {
  //将ni声明为NewInt类型
  var ni NewInt
  //查看ni的类型名,使用%T格式化参数,打印变量ni本身的类型
  fmt.Printf("ni的类型是: %T\n", ni)
  //将ia声明为IntAlias类型
  var ia IntAlias
  // 查看ia的类型名,打印ia变量的类型
  fmt.Printf("ia的类型是: %T\n", ia)

}

 

posted @ 2023-02-18 22:22  jinzi  阅读(3)  评论(0编辑  收藏  举报