Go_type
1. type的定义和使用
Go语言支持函数式编程,可以使用高阶编程语法。一个函数可以作为另一个函数的参数,也可以作为另一个函数的返回值,那么在定义这个高阶函数的时候,如果函数的类型比较复杂,我们可以使用type来定义这个函数的类型。
byte和rune:
在 Go 1.9 版本之前的内建类型定义的代码是这样写的:
type byte uint8 type rune int32
而在 Go 1.9 版本之后变为:
type byte = uint8 //类型别名的作用就让代码更具有可读性 type rune = int32 //存字符,如果是int32,以为是一个数字
package main
import (
"fmt"
"strconv"
)
func main() {
/*
type:用于类型定义和类型别名
1.类型定义:type 类型名 Type //自定义type具有隐藏原type的效果
2.类型别名:type 类型名 = Type
*/
var i1 myint
var i2 = 100 //int
i1 = 200
fmt.Println(i1, i2) //200 100
var name mystr
name = "王二狗"
var s1 string
s1 = "李小花"
fmt.Println(name, s1) //王二狗 李小花
//i1 = i2 //cannot use i2 (type int) as type myint in assignment
//name = s1 //cannot use s1 (type string) as type mystr in assignment
fmt.Printf("%T,%T,%T,%T\n", i1, i2, name, s1) //main.myint,int,main.mystr,string
res1 := fun1()
fmt.Println(res1(10, 20)) //1020
}
//1.定义一个新的类型
type myint int
type mystr string
//2.定义函数类型
type myfun func(int, int) (string)
//返回值是一个函数时,就不需要写那么复杂了
func fun1() myfun { //fun1()函数的返回值是myfun类型
fun := func(a, b int) string {
s := strconv.Itoa(a) + strconv.Itoa(b)
return s
}
return fun
}
//3.类型别名
type myint2 = int //不是重新定义新的数据类型,只是给int起别名,和int可以通用
2. 非本地类型不能定义方法
package main
import "time"
func main() {
}
type MyDuration = time.Duration
//Duration是在time这个包下定义的,现在是在main这个包下修改,是不允许的
//解决方法:
//1.在time这个包下定义
//2.将类型别名改为类型定义: type MyDuration time.Duration,也就是将 MyDuration 从别名改为类型
func (m MyDuration) SimpleSet(){ //cannot define new methods on non-local type time.Duration
}
3. 在结构体成员嵌入时使用别名
package main
import "fmt"
type Person struct {
name string
}
func (p Person) show() {
fmt.Println("Person--->", p.name)
}
//类型别名
type People = Person
func (p People) show2() {
fmt.Println("People--->", p.name)
}
type Student struct {
//嵌入两个结构体
Person
People
}
func main() {
var s Student
//s.name = "王二狗" //ambiguous selector s.name //混淆
s.Person.name = "王二狗"
//s.show() //ambiguous selector s.show
s.Person.show() //Person---> 王二狗
//他们都是Person类型,People只是别名
//虽然是同一类型,但是是两个结构体了
fmt.Printf("%T,%T\n", s.Person, s.People) //main.Person,main.Person
fmt.Printf("%P--%P", &s.Person, &s.People) //&{%!P(string=王二狗)}--&{%!P(string=)}
fmt.Println()
s.People.name = "李小花"
s.People.show() //People---> 李小花
s.People.show2() //People---> 李小花
s.Person.show() //Person---> 王二狗
//s.Person.show2() //没有这个方法
}

浙公网安备 33010602011771号