
1、自定义类型
string Go
typetypeC/C++typedefstructinterface
2、类型定义
2.1 定义结构体
使用 type 可以定义结构体类型:
//1、定义结构体 //结构体定义 type person struct { name string //注意后面不能有逗号 age int }
2.2 定义接口
使用 type 可以定义接口类型:
type USB interface { start() end() }
2.3 定义其他的新类型
type
语法:
type 类型名 Type
示例代码:
type myint int type mystr string func main() { var i1 myint var i2 = 100 i1 = 100 fmt.Println(i1) //i1 = i2 //cannot use i2 (type int) as type myint in assignment fmt.Println(i1,i2) var name mystr name = "王二狗" var s1 string s1 = "李小花" fmt.Println(name) fmt.Println(s1) name = s1 //cannot use s1 (type string) as type mystr in assignment }
2.4 定义函数的类型
Go语言支持函数式编程,可以使用高阶编程语法。一个函数可以作为另一个函数的参数,也可以作为另一个函数的返回值,那么在定义这个高阶函数的时候,如果函数的类型比较复杂,可以使用type来定义这个函数的类型:
func main() { res1 := fun1() fmt.Println(res1(10,20)) } type my_fun func (int,int)(string) //fun1()函数的返回值是my_func类型 func fun1 () my_fun{ fun := func(a,b int) string { s := strconv.Itoa(a) + strconv.Itoa(b) return s } return fun }
3、类型别名
TypeAliasTypeTypeAliasType
类型别名是 Go 1.9 版本添加的新功能。主要用于代码升级、迁移中类型的兼容性问题。在 C/C++语言中,代码重构升级可以使用宏快速定义新的一段代码。Go 语言中没有选择加入宏,而是将解决重构中最麻烦的类型名变更问题。
type TypeAlias = Type
在 Go 1.9 版本之前的内建类型定义的代码是这样写的:
type byte uint8 type rune int32
而在 Go 1.9 版本之后变为:
type byte = uint8 type rune = int32
这个修改就是配合类型别名而进行的修改。
4、类型定义和类型别名的区别
类型别名与类型定义表面上看只有一个等号的差异,我们通过下面的这段代码来理解它们之间的区别。
//类型定义 type NewInt int //类型别名 type MyInt = int func main() { var a NewInt var b MyInt fmt.Printf("type of a:%T\n", a) //type of a:main.NewInt fmt.Printf("type of b:%T\n", b) //type of b:int }
main.NewInt mainNewInt int MyInt MyInt
5、非本地类型不能定义方法
能够随意地为各种类型起名字,是否意味着可以在自己包里为这些类型任意添加方法?
// 定义time.Duration的别名为MyDuration type MyDuration = time.Duration // 为MyDuration添加一个函数 func (m MyDuration) EasySet(a string) { //cannot define new methods on non-local type time.Duration } func main() { }
cannot define new methods on non-local type time.Duration
time.Duration time.Duration main time.Duration time time.Duration main
解决这个问题有下面两种方法:
type MyDuration time.Duration MyDuration time
6、在结构体成员嵌入时使用别名
当类型别名作为结构体嵌入的成员时会发生什么情况?
type Person struct { name string } func (p Person) Show() { fmt.Println("Person-->",p.name) } //类型别名 type People = Person type Student struct { // 嵌入两个结构 Person People } func (p People) Show2(){ fmt.Println("People------>",p.name) } func main() { // var s Student //s.name = "王二狗" //ambiguous selector s.name s.People.name = "李小花" s.Person.name = "王二狗" //s.Show() //ambiguous selector s.Show s.Person.Show() s.People.Show2() fmt.Printf("%T,%T\n",s.Person,s.People) //main.Person,main.Person }
nameShow()nameShow() People Person
以上就是关于“Golang语言中自定义类型有什么,怎么样定义类型”的相关知识,感谢各位的阅读,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注群英网络,小编每天都会为大家更新不同的知识。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。