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包中。

    加油,你们是最棒的!
  • 相关阅读:
    nuxt使用pdfjs-dist插件实现pdf预览
    package.json详细介绍
    encodeURI()和encodeURIComponent() 区别
    前端预览pdf——文件流
    fatal: unable to access 'https://github.com/xxxxx/xxxx.git/': Failed to connect to github.com port 443: Timed out
    vue分隔输入验证码
    Vue简单实现滚动到底部加载数据
    nuxt pdf在线预览
    Eclipse入门-HelloWorld
    多任务学习算法综述
  • 原文地址:https://www.cnblogs.com/Wshile/p/12678840.html
Copyright © 2011-2022 走看看