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

    加油,你们是最棒的!
  • 相关阅读:
    fastadmin自定义列表下拉框筛选
    printf输出16进制和对齐, fprintf的运用
    微信小程序代码提交发布之后,必须删除原来的小程序才会更新到最新的代码
    win 内存优化
    CRT工具 直连AMZ主机
    解决Jumpserver邮件不发送
    NxShell
    Photoshop 2022 破解版下载
    IDA Pro7.7破解版下载
    MAC下调用已打开浏览器的方法
  • 原文地址:https://www.cnblogs.com/Wshile/p/12678840.html
Copyright © 2020-2023  润新知