27、Type关键字

发布时间 2023-09-30 23:39:02作者: 我也有梦想呀

1、是什么?

type是go语法里额重要而且常用的关键字,type绝不只是对应于C/C++中的typeof。搞清楚type的使用,就容易理解Go语言中的核心概念struct、interface、函数等的作用

2、怎么玩?

(1) 定义结构体
// 使用type定义结构体
type Person struct {
	name string
	age  int
}
(2) 定义接口类型
type PersonService interface {
	addPerson(p Person) int
}
(3) 定义新类型
// 定义新类型
type myint int
type mystr string

var i1 myint
	var i2 int
	i1 = 100
	i2 = 200
	fmt.Println(i1)
	fmt.Println(i2)

	var name mystr
	var s1 string
	name = "ly"
	s1 = "张三"
	fmt.Println(name)
	fmt.Println(s1)

	i2 = i1 // cannot use i1 (variable of type myint) as type int in assignment
	// s1 = name
(4) 定义函数类型
type myFun func(int, int) string
func fun1() myFun {
	fun := func(a, b int) string {
		s := strconv.Itoa(a) + strconv.Itoa(b)
		return s
	}
	return fun
}
(5) 类型别名
type myint2 = int // 给 int 类型取别名和int类型是通用的

var a myint2
	var b myint2
	a = 100
	b = 200
	b = i2
	fmt.Printf("%T,%T,%T \n", a, b, i2)

image

注意:非本地类型不能定义方法

代码
/**
 * @author ly (个人博客:https://www.cnblogs.com/ybbit)
 * @date 2023/9/30  23:22
 * @tags 喜欢就去努力的争取
 */
package main

import "fmt"

func main() {
	var s Student
	// s.name // ambiguous selector s.name
	s.People.name = "people"
	s.Person.name = "Person"
	s.People.show()
	s.Person.show()
}

type Person struct {
	name string
}

type People = Person

type Student struct {
	Person
	People
}

func (p Person) show() {
	fmt.Println("show方法执行了", p.name)
}

/**
 * @author ly (个人博客:https://www.cnblogs.com/ybbit)
 * @date 2023/9/30  14:56
 * @tags 喜欢就去努力的争取
 */
package main

import (
	"fmt"
	"strconv"
)

func main() {

	var i1 myint
	var i2 int
	i1 = 100
	i2 = 200
	fmt.Println(i1)
	fmt.Println(i2)

	var name mystr
	var s1 string
	name = "ly"
	s1 = "张三"
	fmt.Println(name)
	fmt.Println(s1)

	// i2 = i1 // cannot use i1 (variable of type myint) as type int in assignment
	// s1 = name

	fmt.Printf("%T,%T,%T,%T \n", i1, i2, name, s1)

	res := fun1()
	fmt.Println(res(10, 20))

	var a myint2
	var b myint2
	a = 100
	b = 200
	b = i2
	fmt.Printf("%T,%T,%T \n", a, b, i2)

}

type myint2 = int // 给 int 类型取别名和int类型是通用的

// 定义函数类型
type myFun func(int, int) string

func fun1() myFun {
	fun := func(a, b int) string {
		s := strconv.Itoa(a) + strconv.Itoa(b)
		return s
	}
	return fun
}

// 定义新类型
type myint int
type mystr string

// 使用type定义结构体
type Person struct {
	name string
	age  int
}

// 定义接口
type PersonService interface {
	add(person Person) int
}