美文网首页Go
Go语言 type关键字

Go语言 type关键字

作者: 小杰的快乐时光 | 来源:发表于2018-08-18 23:43 被阅读0次

    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")
          }
       }
    }
    

    相关文章

      网友评论

        本文标题:Go语言 type关键字

        本文链接:https://www.haomeiwen.com/subject/qjdqiftx.html