当前位置:   article > 正文

golang基础小记(13)——自定义类型和类型别名(type)_golang .type()==string

golang .type()==string

自定义类型

Go语言通过type关键字定义自定义类型。自定义类型是全新的类型。
示例:

// 将newInt定义为int类型
type newInt int

func main() {
	var a newInt
	a = 100
	fmt.Println(a)        // 100
	fmt.Printf("%T\n", a) // main.newInt
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

上例中的newInt是具有int特性的新类型。可以看到变量a的类型是main.newInt,这表示main包下定义的newInt类型。

类型别名

语法格式:type 别名 = Type
示例:

type tempString = string

func main() {
	var s tempString
	s = "我是s"
	fmt.Println(s)        // 我是s
	fmt.Printf("%T\n", s) // string
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

上例中,tempStringstring的别名,其本质上与string是同一个类型。类型别名只会在代码中存在,编译完成后不会有如tempString一样的类型别名。所以变量s的类型是string
字符类型中的byterune就是类型别名:

type byte = uint8
type rune = int32
  • 1
  • 2

参考

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/42939
推荐阅读
相关标签
  

闽ICP备14008679号