Go语言中type的用法
Go语言中type的用法:
1.定义结构体类型
2.类型别名
3.定义接口类型
4.定义函数类型
1.定义结构体类型
结构体可用于用户自定义数据类型和进行面向对象编程。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | type Person struct { name string age int sex bool } func (p *Person)Eat(){ fmt.Printf( "%s爱吃西红柿炒鸡蛋\n" ,p.name) } func (p *Person)Drink(){ fmt.Printf( "%s爱喝可乐\n" ,p.name) } func (p *Person)Sleep(){ fmt.Printf( "%s要睡8个小时\n" ,p.name) } func (p *Person)Love(){ fmt.Printf( "%s喜欢\n" ,p.name) } |
2.类型别名
type str string
str类型与string类型等价
例子:
package main import "fmt" type str string func main () { var myname str = "Ling" fmt.Printf("%s",myname) }
3.定义接口
type Shaper interface {
Area() float64
}
接口定义了一个 方法的集合,但是这些方法不包含实现代码,它们是抽象的,接口里也不能包含变量。
注意实现接口可以是结构体类型,也可以是函数类型。
4.定义函数类型
当不定义函数类型,传递函数时:
package main import "fmt" func isOdd(integer int) bool { if integer%2 == 0 { return false } return true } func isEven(integer int) bool { if integer%2 == 0 { return true } return false } func filter(slice []int, f func(int) bool) []int { var result []int for _, value := range slice { if f(value) { result = append(result, value) } } return result } func test(){ slice := []int {1, 2, 3, 4, 5, 7} fmt.Println("slice = ", slice) odd_res := filter(slice, isOdd) // 函数当做值来传递了 fmt.Println("Odd elements of slice are: ", odd_res) even_res := filter(slice, isEven) // 函数当做值来传递了 fmt.Println("Even elements of slice are: ", even_res) } func main(){ test() }
当定义函数类型,传递函数时:
package main import "fmt" type functinTyoe func(int) bool // 声明了一个函数类型 func isOdd(integer int) bool { if integer%2 == 0 { return false } return true } func isEven(integer int) bool { if integer%2 == 0 { return true } return false } // 声明的函数类型在这个地方当做了一个参数 func filter(slice []int, f functinTyoe) []int { var result []int for _, value := range slice { if f(value) { result = append(result, value) } } return result } func test(){ slice := []int {1, 2, 3, 4, 5, 7} fmt.Println("slice = ", slice) odd_res := filter(slice, isOdd) // 函数当做值来传递了 fmt.Println("Odd elements of slice are: ", odd_res) even_res := filter(slice, isEven) // 函数当做值来传递了 fmt.Println("Even elements of slice are: ", even_res) } func main(){ test()
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
2019-02-13 数据库学习之多表操作(三)
2019-02-13 Linux学习之源码包安装与脚本安装(十八)