go内置数据类型(五)

  • 2023-08-15 14:35:16
  • 613
  • 0
  • go
  • authen

一、结构体

1.1、定义

Go语言中没有“类”的概念,也不支持“类”的继承等面向对象的概念。Go语言中通过结构体的内嵌再配合接口比面向对象具有更高的扩展性和灵活性。

Go语言中的基础数据类型可以表示一些事物的基本属性,但是当我们想表达一个事物的全部或部分属性时,这时候再用单一的基本数据类型明显就无法满足需求了,Go语言提供了一种自定义数据类型,可以封装多个基本数据类型,这种数据类型叫结构体,英文名称struct。 也就是我们可以通过struct来定义自己的类型了。Go语言中通过struct来实现面向对象。

使用type和struct关键字来定义结构体,具体代码格式如下:

 type 类型名 struct {
        字段名 字段类型
        字段名 字段类型
        …
    }
其中:
    1.类型名:标识自定义结构体的名称,在同一个包内不能重复。
    2.字段名:表示结构体字段名。结构体中的字段名必须唯一。
    3.字段类型:表示结构体字段的具体类型。

举个例子,我们定义一个Person(人)结构体,代码如下:

type person struct {
        name string
        city string
        age  int8
    }
同样类型的字段也可以写在一行,
    type person1 struct {
        name, city string
        age        int8
    }

1.2、实例化

type person struct {
    name string
    city string
    age  int8
}

func main() {
    var p1 person
    p1.name = "pprof.cn"
    p1.city = "北京"
    p1.age = 18
    fmt.Printf("p1=%v\n", p1)  //p1={pprof.cn 北京 18}
    fmt.Printf("p1=%#v\n", p1) //p1=main.person{name:"pprof.cn", city:"北京", age:18}
}

2.1、自定义类型

 

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

 

2.2、类型别名

我们之前见过的rune和byte就是类型别名,他们的定义如下:

    type byte = uint8
    type rune = int32

 

2.3、类型别名与类型定义表面上看只有一个等号的差异,我们通过下面的这段代码来理解它们之间的区别。

//类型定义
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
}

 

阅读更多

go内置数据类型(四)

  • 2023-08-15 11:31:31
  • 411
  • 0
  • go
  • authen

一、sort包

1、内置正排序:

package main

import (
	"fmt"
	"sort"
)

func main() {
	intSlice := []int{3, 1, 2, 5, 4}
	float64Slice := []float64{3.2, 1.0, 2.1, 5.4, 4.3}
	stringSlice := []string{"abcd", "aacd", "bcda", "d"}

	sort.Ints(intSlice)			//1, 2, 3, 4, 5
	sort.Float64s(float64Slice)	//1.0, 2.1, 3.2, 4.3, 5.4
	sort.Strings(stringSlice)	//"aacd", "abcd", "bcda", "d"
}

2、内置倒排序

package main

import (
	"fmt"
	"sort"
)

func main() {
	intSlice := []int{3, 1, 2, 5, 4}
	float64Slice := []float64{3.2, 1.0, 2.1, 5.4, 4.3}
	stringSlice := []string{"abcd", "aacd", "bcda", "d"}

	sort.Sort(sort.Reverse(sort.IntSlice(intSlice)))
	//5, 4, 3, 2, 1
	sort.Sort(sort.Reverse(sort.Float64Slice(float64Slice)))
	//5.4, 4.3, 3.2, 2.1, 1.0
	sort.Sort(sort.Reverse(sort.StringSlice(stringSlice)))
	//"d", "bcda", "abcd", "aacd"
}

 

阅读更多

go内置数据类型(三)

  • 2023-08-15 09:55:44
  • 367
  • 0
  • go
  • authen

一、context

在 Go http包的Server中,每一个请求在都有一个对应的 goroutine 去处理。请求处理函数通常会启动额外的 goroutine 用来访问后端服务,比如数据库和RPC服务。用来处理一个请求的 goroutine 通常需要访问一些与请求特定的数据,比如终端用户的身份认证信息、验证相关的token、请求的截止时间。 当一个请求被取消或超时时,所有用来处理该请求的 goroutine 都应该迅速退出,然后系统才能释放这些 goroutine 占用的资源。

 

阅读更多