Golang Basic 8 - Pointer

Golang Basic 8 - Pointer

Pointer

  • A pointer holds the memory address of a value.

Declear

  • Pointers in Golang are very similar to pointers in c/c .
    // declear a pointer
    var pointerName *dataType
    
    //get a pointer's value
    *pointerName
    
    //get a variable's physical address
    &variableName
    

    Sample

    root@go:l8/ # cat l8s1.go
    package main
    import (
        "fmt"
    )
    
    func swap(val1 *int, val2 *int){
        *val1, *val2 = *val2, *val1
    
    }
    
    func main(){
        var var1, var2 int
        var1 = 3
        var2 = 6
        fmt.Println(var1, var2)
        swap(&var1, &var2)
        fmt.Println(var1, var2)
    
    }
    root@go:l8/ # go run l8s1.go
    3 6
    6 3
    

发表评论

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据