Golang中的type关键字


原文链接
type有几种用法:定义结构体,定义接口, 类型别名, 类型定义, 类型开关

定义结构体

结构体是由一系列具有相同类型或不同类型的数据构成的数据集合。类似Java 的类,我们可以把Go中的struct看作是不支持继承行为的轻量级的“类”。
我们来看看使用type怎么定义结构体:

//定义一个 Books结构体
type Books struct {
   title string
   author string
   subject string
   book_id int
}

//结构体内内嵌匿名成员变量定义
func main() {
   p := person{"abc",12}
   fmt.Println(p.string,p.int)
}

type person struct {
   string
   int
}

定义接口

//定义电话接口
type Phone interface {
   call()
}

自定义类型

type name string   // 使用 type 基于现有基础类型,结构体,函数类型创建用户自定义类型。
  • 在这里要区别 var声明方式
var name string    //这里是定义一个string变量

注:类型别名,只能对包内的类型产生作用,对包外的类型采用类型别名,在编译时将会提示如下信息:


cannot define new methods on non-local type string

类型定义

除了给已知的类型起别名,还可以针对新类型(自定义类型)函数进行定义

type handle func(str string)  //自定义一个函数func,别名叫做handle,传入一个string参数

类型开关

在Go语言中中存在interface{}类型,可以用来保存任何类型的值,如果我们需要知道具体保存了哪些类型,就需要使用类型开关来判断,具体代码如下:

func classifier(items ...interface{})  {
   for i,x := range items {
      switch x.(type) {
      case bool:
         fmt.Printf("type #%d is bool",i)
      case float64:
         fmt.Printf("type #%d is float64",i)
      case string:
         fmt.Printf("type #%d is string",i)
      case int:
         fmt.Printf("type #%d is int",i)
      default:
         fmt.Printf("type is unknow")
      }
   }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值