教程: 内置类型和函数


基本的main.go

package main

import "fmt"

func main() {
    var helloStr string
    helloStr = "Hello World!"
    helloStr2 := helloStr
    fmt.Println(helloStr)
    fmt.Println(helloStr2)
}
# 输出
Hello World!
Hello World!

内置类型

  • 布尔 : bool

  • 整型 : int int8 int16 int32 int64

    • int 根据操作系统决定是 int32 还是 int64
  • 无符号整型 : uint uint8 uint16 uint32 uint64 uintptr

    • uint 根据操作系统决定是 uint32 还是 uint64
    • uintptr 是存储指针的 uint32uint64 整数
  • 整型变体 :

    • byte : uint8 的别名
    • rune : int32的别名,代表一个 Unicode码
  • 指针 :
    初始化: var aPtr *int = &aInt
    初始化: var aPtr *int = new(int)

  • 浮点 : float32 float64

  • 复数 : complex64 complex128

  • 字符串 : string

  • 数组(固定长度的数组) : 使用 [5]int 表示
    初始化: aArray := [...]int{1, 2, 3, 4, 5, 6}

  • 切片(长度不固定) : 使用 []int 表示
    初始化: aSlice := []int{}
    初始化: aSlice := make([]int, 0, 0)

  • 映射 : 使用 map[string]int 表示
    初始化: aMap := map[string]int{}
    初始化: aMap := make(map[string]int, 8)

  • 管道 : 使用 chan int 表示

    • 初始化: aChannel := make(chan int)
    • 只读单向管道使用 <-chan int 表示
    • 只写单向管道使用 chan<- int 表示
  • 结构体struct : type Student struct {}

    • 其实是使用了 type {NewTypeName} {OldTypeName} 语法, 创建自定义类型, 例如 type MyInt int
    • 如果是 type MyInt = int 则其实 MyIntint 等价, 这被称为类型别名
  • 函数function :

  • error接口: error , 任何实现了 Error() String 方法的对象都可以认为是 error 类型

error接口

type error interface {
  Error() String
}

示例代码

package main

import "fmt"

func main() {
    aArray1 := [...]int{1, 2, 3, 4, 5, 6}
    aArray2 := [5]int{1, 2, 3, 4}
    fmt.Println("aArray1 is ", aArray1)
    fmt.Println("aArray2 is ", aArray2)

    fmt.Println("===============")
    aSlice1 := []int{}
    aSlice2 := make([]int, 10, 10)
    fmt.Println("aSlice1 is ", aSlice1)
    fmt.Println("aSlice2 is ", aSlice2)

    fmt.Println("===============")
    aMap1 := map[int]int{}
    aMap2 := make(map[int]int, 8)
    fmt.Println("aMap1 is ", aMap1)
    fmt.Println("aMap2 is ", aMap2)

    fmt.Println("===============")
    var aChan1 chan int = make(chan int)
    aChan2 := make(<-chan int)
    aChan3 := make(chan<- int)
    fmt.Println("aChan1 is ", aChan1)
    fmt.Println("aChan2 is ", aChan2)
    fmt.Println("aChan3 is ", aChan3)

    fmt.Println("===============")
    type Student struct {
        age int
    }
    aStu := Student{}
    fmt.Println("aStu is ", aStu)

    fmt.Println("===============")
    aFunc := func(a int, b int) int {
        return a + b
    }
    fmt.Println("aFunc is ", aFunc)

    fmt.Println("===============")
    var aInterface interface{}
    aInterface=aStu
    fmt.Println("aInterface is ", aInterface)
}
# 输出
aArray1 is  [1 2 3 4 5 6]
aArray2 is  [1 2 3 4 0]
===============
aSlice1 is  []
aSlice2 is  [0 0 0 0 0 0 0 0 0 0]
===============
aMap1 is  map[]
aMap2 is  map[]
===============
aChan1 is  0xc000052060
aChan2 is  0xc0000520c0
aChan3 is  0xc000052120
===============
aStu is  {0}
===============
aFunc is  0x47cde0
===============
aInterface is  {0}

内置函数


初始化变量的函数

  • make : 仅用于初始化 slice , map , chan
  • new : 仅用于初始化除 slice , map , chan 之外的其他类型的指针类型
  • slice , map , chan 之外的其他类型声明即赋予相对于其类型的零值, 例如 var aBool bool , aBool 被赋予 false

示例代码

package main

import "fmt"

func main() {
    var aPointer *int
    aPointer = new(int)
    fmt.Println("aPointer is ", aPointer)

    fmt.Println("===============")
    var aSlice []int
    aSlice = make([]int, 10, 10)
    fmt.Println("aSlice is ", aSlice)

    fmt.Println("===============")
    var aMap map[int]int
    aMap = make(map[int]int, 8)
    fmt.Println("aMap is ", aMap)

    fmt.Println("===============")
    var aChan chan int
    aChan = make(chan int)
    fmt.Println("aChan is ", aChan)
}
# 输出
aPointer is  0xc0000aa058
===============
aSlice is  [0 0 0 0 0 0 0 0 0 0]
===============
aMap is  map[]
===============
aChan is  0xc000086060


关于数组切片的函数

  • append : 向切片中追加元素 , aSlice = append(aSlice, 1)

  • len : 获取数组或切片的长度 , len(aSlice)

  • cap : 获取数组或切片的容量 , cap(aSlice)

  • 遍历 : for index,value := range aSlice {

  • 切片截取 :

    • aSlice[low:high:max] 得到的结果的 len=high-low , cap=max-low , high和max的值不能大于 原切片的capacity
    • aSlice[low:high]
    • aSlice[low:]
    • aSlice[:high]aSlice[:high:max]
  • 关于复制的函数copy :
    copy : copy(dst,src) 根据 srclendstlen 拷贝内容 , 例如 n4 := copy(s[3:], a[5:])a 数组中第6个元素至最后一个元素 依次拷贝到 s 切片中第4个元素位置,直到拷贝完成或到达 s 切片的 len 限制

示例代码

package main

import "fmt"

func main() {
    var aSlice []int
    aSlice = make([]int, 0, 1)
    fmt.Println("cap(aSlice) is ", cap(aSlice))
    aSlice = append(aSlice, 1)
    aSlice = append(aSlice, 2)
    aSlice = append(aSlice, 3)
    fmt.Println("aSlice is ", aSlice)
    fmt.Println("len(aSlice) is ", len(aSlice))
    fmt.Println("cap(aSlice) is ", cap(aSlice))

    fmt.Println("=======遍历示例=====")
    for i, v := range aSlice {
        fmt.Println("index:", i, "value:", v)
    }

    fmt.Println("============")
    aSlice2:=aSlice[1:4:4]
    fmt.Println("aSlice2 is ", aSlice2)
    fmt.Println("len(aSlice2) is ", len(aSlice2))
    fmt.Println("cap(aSlice2) is ", cap(aSlice2))

    fmt.Println("============")
    aSlice3:=make([]int,1,4)
    copy(aSlice3[0:],aSlice)
    fmt.Println("aSlice3 is ", aSlice3)
    fmt.Println("len(aSlice3) is ", len(aSlice3))
    fmt.Println("cap(aSlice3) is ", cap(aSlice3))
}
# 输出
cap(aSlice) is  1
aSlice is  [1 2 3]
len(aSlice) is  3
cap(aSlice) is  4
=======遍历示例=====
index: 0 value: 1
index: 1 value: 2
index: 2 value: 3
============
aSlice2 is  [2 3 0]
len(aSlice2) is  3
cap(aSlice2) is  3
============
aSlice3 is  [1]
len(aSlice3) is  1
cap(aSlice3) is  4

关于映射的函数

  • 从map中删除key: delete(scene, "brazil")
  • delete可以删除不存在的key
  • delete函数不返回任何值
  • 获取key对应的值: value := map[key] 不会失败,如果key不存在,则返回类型对应的零值
  • 判断键是否存在 : value, ok := map[key]
  • 遍历 : for key,value := range aMap {
  • 只遍历key : for key := range aMap {
package main

import "fmt"

func main() {
    var aMap map[string]int
    aMap = make(map[string]int, 8)
    fmt.Println("aMap is ", aMap)
    fmt.Println("len(aMap) is ", len(aMap))
    aMap["张三"] = 90
    aMap["小明"] = 100
    fmt.Println("============")
    fmt.Println("aMap is ", aMap)
    fmt.Println("len(aMap) is ", len(aMap))
    fmt.Println("aMap[\"张三\"] is ", aMap["张三"])
    fmt.Println("aMap[\"李四\"] is ", aMap["李四"]) //获取不存在的key,返回类型对应的零值
    if value, ok := aMap["李四"]; ok {
        fmt.Println("aMap[\"李四\"] is ", value)
    } else {
        fmt.Println("aMap[\"李四\"] is not exists ")
    }
    fmt.Println("=======遍历示例1=====")
    for k, v := range aMap {
        fmt.Println("key:", k, "value:", v)
    }

    fmt.Println("=======遍历示例2=====")
    for k := range aMap {
        fmt.Println("key:", k, "value:", aMap[k])
    }

    fmt.Println("============")
    delete(aMap, "张三")
    fmt.Println("aMap is ", aMap)
    fmt.Println("len(aMap) is ", len(aMap))
    delete(aMap, "张三") // 可以删除不存在的key

}
# 输出
aMap is  map[]
len(aMap) is  0
============
aMap is  map[小明:100 张三:90]
len(aMap) is  2
aMap["张三"] is  90
aMap["李四"] is  0
aMap["李四"] is not exists 
=======遍历示例1=====
key: 张三 value: 90
key: 小明 value: 100
=======遍历示例2=====
key: 张三 value: 90
key: 小明 value: 100
============
aMap is  map[小明:100]
len(aMap) is  1

关于管道的函数

  • 关闭 chan : close(aChan)

关于异常恢复的函数

  • panic :
  • recover :

关于字符串的函数

  • 获取字符串长度(bytes长度): len(str)
  • 获取字符串长度(字符长度,含中文): len([]rune(str))
  • 遍历字符串: for _, r := range s { //rune
  • 拼接字符串 : 使用 +fmt.Sprintf
  • 分割字符串: 使用 strings.Split
  • join字符串: strings.Join(a[]string, sep string)
  • 判断是否包含: strings.Contains
  • 前缀/后缀判断 : strings.HasPrefix , strings.HasSuffix
  • 子串出现的位置: strings.Index() , strings.LastIndex()
package main

import (
    "fmt"
    "strings"
)

func main() {
    var aStr string
    aStr="Hello世界!"
    fmt.Println("len(aStr) is ", len(aStr))
    fmt.Println("len(aStr) is ", len([]rune(aStr)))

    fmt.Println("=====遍历字符串=======")
    for i,v := range aStr { //rune
        fmt.Println(i,string(v))
    }

    fmt.Println("============")
    aStr2:=aStr+"拼接字符串"
    fmt.Println("aStr2 is ", aStr2)
    aStr3:=fmt.Sprintf("%s拼接字符串",aStr)
    fmt.Println("aStr3 is ", aStr3)

    fmt.Println("============")
    aSlice:=strings.Split(aStr,"o")
    fmt.Println("strings.Split(aStr,\"o\") is ", aSlice)
    aStr4:=strings.Join(aSlice,"...")
    fmt.Println("strings.Join(aSlice,\"...\") is ", aStr4)

    fmt.Println("============")
    fmt.Println("strings.ContainsAny(aStr,\"ll\") is ", strings.ContainsAny(aStr,"ll"))
    fmt.Println("strings.HasPrefix(aStr,\"He\") is ", strings.HasPrefix(aStr,"He"))
    fmt.Println("strings.HasSuffix(aStr,\"世界!\") is ", strings.HasSuffix(aStr,"世界!"))
    fmt.Println("strings.Index(aStr,\"l\") is ", strings.Index(aStr,"l"))
    fmt.Println("strings.LastIndex(aStr,\"l\") is ", strings.LastIndex(aStr,"l"))
}
# 输出
len(aStr) is  12
len(aStr) is  8
=====遍历字符串=======
0 H
1 e
2 l
3 l
4 o
5 世
8 界
11 !
============
aStr2 is  Hello世界!拼接字符串
aStr3 is  Hello世界!拼接字符串
============
strings.Split(aStr,"o") is  [Hell 世界!]
strings.Join(aSlice,"...") is  Hell...世界!
============
strings.ContainsAny(aStr,"ll") is  true
strings.HasPrefix(aStr,"He") is  true
strings.HasSuffix(aStr,"世界!") is  true
strings.Index(aStr,"l") is  2
strings.LastIndex(aStr,"l") is  3

关于复数的函数

  • complex : 生成复数, var x complex128 = complex(1, 2) // 1+2i
  • real : 获取复数的实部 real(x*y)
  • imag : 获取复数的虚部 imag(x*y)
package main

import (
    "fmt"
)

func main() {
    var aComplex complex128
    aComplex = complex(1, 2)
    fmt.Println("aComplex is ", aComplex)
    fmt.Println("real(aComplex) is ", real(aComplex))
    fmt.Println("imag(aComplex) is ", imag(aComplex))
}
# 输出
aComplex is  (1+2i)
real(aComplex) is  1
imag(aComplex) is  2

你可能感兴趣的:(教程: 内置类型和函数)