zoukankan      html  css  js  c++  java
  • <5>Golang基础进阶——类型别名

    Golang:类型别名

    1. 区分类型别名与类型定义

    类型别名的写法为:

    type TypeAlias = Type

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

    类型别名和类型定义代码示例:

    // NewInt 定义为int类型
    type NewInt int

    // int 个别名IntAlias
    type IntAlias = int

    func main() {
    // a声明为NewInt类型
    var a NewInt
    // 查看a的类型名
    fmt.Printf("a type: %T ", a)

    // a2声明为IntAlias类型
    var a2 IntAlias
    fmt.Printf("a2 type: %T ", a2)

    }

    // 输出结果:
    //a type: main.NewInt
    //a2 type: int

    结果显示a类型是 main.NewInt 表示 main 包下定义的 NewInt 类型。 a2 类型是 int。IntAlias 类型只会在代码中存在,编译完成时,不会有 IntAlias 类型。

    2. 非本地类型不能定义方法

    能够随意地为各种类型起名字,是否意味着可以在自己包里为这些类型任意添加方法?

    // 定义time.Duration的别名为MyDuration
    type MyDuration = time.Duration

    func (m MyDuration) EasySet(a string) {

    }

    func main() {

    }

    // 输出结果:
    //cannot define new methods on non-local type time.Duration

    编译器提示:不能在一个非本地的类型 time.Duration 上定义新方法。
     time.Duration 在time包中,但是在main包中定义是不允许的。

    解决方法:

    1. 将别名修改为类型定义:type MyDuration time.Duration。

    2. 将MyDutation的别名定义放在time包中。

    加油,你们是最棒的!
  • 相关阅读:
    摄像机模型 (Camera Model)
    TP中如何用IF
    Mysql连接报错:1130-host ... is not allowed to connect to this MySql server如何处理
    LNMP环境源码搭建
    Linux之不得不说的init(Linux启动级别的含义 init 0-6)
    PHP 生成毫秒时间戳
    Linux Bash Shell字符串截取
    Linux crontab任务调度
    下载百度文库文档
    关于java socket中的read方法阻塞问题
  • 原文地址:https://www.cnblogs.com/Wshile/p/12678840.html
Copyright © 2011-2022 走看看