Go语言基础——内置函数

Go语言基础

内置类型

值类型:

   bool
    int(32 or 64), int8, int16, int32, int64
    uint(32 or 64), uint8(byte), uint16, uint32, uint64
    float32, float64
    string
    complex64, complex128
    array    -- 固定长度的数组

引用类型:(指针类型)

  slice   -- 序列数组(最常用)
    map     -- 映射
    chan    -- 管道

内置函数

  • make():用于创建一个新的slice、map或channel。make()函数的参数包括要创建的类型、长度和容量等。
    // 创建一个长度为5,容量为10的slice
    s := make([]int, 5, 10)
    fmt.Println(len(s)) // 5
    fmt.Println(cap(s)) // 10
    
    // 创建一个长度为5,容量为5的map
    m := make(map[string]int, 5)
    m["one"] = 1
    fmt.Println(m) // map[one:1]
    
    // 创建一个容量为10的channel
    c := make(chan int, 10)
    c <- 1
    fmt.Println(<-c) // 1
    
  • append():用于向slice中添加元素。如果slice的容量不足,append()函数会自动扩容。
    // 向slice中添加元素
    s := []int{
          
          1, 2, 3}
    s = append(s, 4, 5, 6)
    fmt.Println(s) // [1 2 3 4 5 6]
    
  • len():用于获取slice、map、string、array和channel等类型的长度。
    s := []int{
          
          1, 2, 3, 4, 5}
    fmt.Println(len(s)) // 5
    
    m := map[string]int{
          
          "one": 1, "two": 2, "three": 3}
    fmt.Println(len(m)) // 3
    
    str := "hello"
    fmt.Println(len(str)) // 5
    
    arr := [5]int{
          
          1, 2, 3, 4, 5}
    fmt.Println(len(arr)) // 5
    
    c := make(chan int, 10)
    c <- 1
    fmt.Println(len(c)) // 1
    
  • cap():用于获取slice、array和channel等类型的容量。
    s := []int{
          
          1, 2, 3, 4, 5}
    fmt.Println(cap(s)) // 5
    
    arr := [5]int{
          
          1, 2, 3, 4, 5}
    fmt.Println(cap(arr)) // 5
    
    c := make(chan int, 10)
    fmt.Println(cap(c)) // 10
    
  • copy():用于复制slice中的元素到另一个slice中。
    
    s1 := []int{
          
          1, 2, 3, 4, 5}
    s2 := make([]int, len(s1))
    copy(s2, s1)
    fmt.Println(s2) // [1 2 3 4 5]
    
  • close():用于关闭一个channel。
    c := make(chan int, 10)
    c <- 1
    close(c)
    fmt.Println(<-c) // 1
    _, ok := <-c
    fmt.Println(ok) // false
    
  • delete():用于删除map中的元素。
    m := map[string]int{
          
          "one": 1, "two": 2, "three": 3}
    delete(m, "two")
    fmt.Println(m) // map[one:1 three:3]
    
  • panic()和recover():用于处理Go语言的异常。
    func test() {
          
          
        defer func() {
          
          
            if err := recover(); err != nil {
          
          
                fmt.Println("panic:", err)
            }
        }()
        panic("test panic")
    }
    
    func main() {
          
          
        test()
        fmt.Println("after test")
    }
    // 输出:panic: test panic
    
    这是因为在test()函数中调用了panic()函数,导致程序发生了异常,然后通过defer语句中的匿名函数实现了异常的捕获和处理。具体地,defer语句会将一个匿名函数压入函数调用栈中,等待当前函数执行完毕后再执行该匿名函数。在本例中,匿名函数中使用了recover()函数来捕获异常,并将异常信息输出到控制台。由于recover()函数只有在defer语句中才能生效,因此需要将其放在defer语句中。最后,main()函数继续执行,输出了after test
  • print()和println():用于输出内容到终端。
    name := "Alice"
    age := 20
    fmt.Print("My name is ", name, ", and I'm ", age, " years old.")
    // 输出:My name is Alice, and I'm 20 years old.
    
    fmt.Println("My name is ", name, ", and I'm ", age, " years old.")
    // 输出:
    // My name is Alice, and I'm 20 years old.
    // (自动换行)
    

内置接口error

  type error interface {
    
     //只要实现了Error()函数,返回值为String的都实现了err接口

            Error()    String

    }

可以看到,error接口只包含了一个Error()方法,该方法返回一个字符串类型的错误信息。因此,如果我们想要自定义一个错误类型,只需要实现Error()方法即可。

以下是一个自定义错误类型的示例,该错误类型表示除数为0的错误:

type DivideError struct {
    
    
    dividend int
    divisor  int
}

func (de *DivideError) Error() string {
    
    
    return fmt.Sprintf("error: divide %d by %d", de.dividend, de.divisor)
}

func divide(dividend, divisor int) (int, error) {
    
    
    if divisor == 0 {
    
    
        return 0, &DivideError{
    
    dividend, divisor}
    }
    return dividend / divisor, nil
}

func main() {
    
    
    result, err := divide(10, 0)
    if err != nil {
    
    
        fmt.Println(err)
    } else {
    
    
        fmt.Println(result)
    }
}

在该示例中,我们定义了一个DivideError结构体,该结构体包含了被除数和除数两个变量。然后,我们为该结构体定义了一个Error()方法,用于返回除数为0的错误信息。接着,我们定义了一个divide()函数,该函数用于计算两个数的商,并返回计算结果和错误信息。如果除数为0,则返回一个DivideError类型的错误。最后,在main()函数中调用divide()函数,如果返回的错误不为空,则输出错误信息;否则输出计算结果。

总之,error接口是Go语言中一个非常常用的接口,用于表示错误信息。在实际开发中,我们经常会使用error接口来自定义错误类型,并将错误信息返回给调用者。通过合理地使用error接口,我们可以提高程序的容错能力和健壮性。

猜你喜欢

转载自blog.csdn.net/m0_60496161/article/details/130836218