Go-Type

被刻印的时光 ゝ 提交于 2019-12-05 01:36:50

在谈论structinterface已经用到了type这个关键字。

另外,Go的type另外一种常用功能,是类似于C/C++的typedef。在Go的package中,这种用法非常常见。

A type declaration defines a new named type that has the same underlying type as an existing type. The named type provides a way to separate different and perhaps incompatible uses of the underlying type so that they can’t be mixed unintentionally.

type name underlying-type

示例:

package main 

import (
    "fmt"
)

type Hello interface {
    out()
}

type MyInt int 

func (myInt *MyInt) out() {
    fmt.Println("MyInt.out():", *myInt)
}

func foo(i MyInt) {
    fmt.Println("foo():", i)
}

func main() {
    var i MyInt 
    i = 5 
    i.out() //MyInt.out(): 5
    foo(i) // foo(): 5
    foo(1) // foo(): 1

    var x int 
    x = 100 
    //foo(x) //cannot use x (type int) as type MyInt in argument to foo
    foo(MyInt(x)) // foo(): 100
}

注:foo(MyInt(x)) 给出了Go中强制类型转换的使用示例。——和C/C++的类型转换语法刚好相反(e.g. foo((MyInt)x))。

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!