Go-Type

u013344915 · · 3075 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

在谈论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))。


有疑问加站长微信联系(非本文作者)

本文来自:CSDN博客

感谢作者:u013344915

查看原文:Go-Type

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

3075 次点击  
加入收藏 微博
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传