Golang 如何找到指针的长度

Golang 如何找到指针的长度

Go编程语言或Golang中的指针是一个变量,用来存储另一个变量的内存地址。Golang中的指针也被称为特殊变量。这些变量用于在系统中的特定内存地址上存储一些数据。内存地址总是以十六进制格式(以0x开头,如0xFFAAF等)。
在指针中,你可以在 len() 函数的帮助下找到指针的长度。这个函数是一个内置函数,它返回数组指针中存在的元素总数,即使指定的指针为零。这个函数被定义在内置函数下。

语法

func len(l Type) int

这里, l 的类型是一个指针。让我们借助给定的例子来讨论这个概念。

例子

// Go program to illustrate how to find the
// length of the pointer to an array
package main
  
import (
    "fmt"
)
  
// Main function
func main() {
  
    // Creating and initializing
    // pointer to array
    // Using var keyword
    var ptr1 [6]*int
    var ptr2 [3]*string
    var ptr3 [4]*float64
  
    // Finding the length of 
    // the pointer to array
    // Using len function
    fmt.Println("Length of ptr1: ", len(ptr1))
    fmt.Println("Length of ptr2: ", len(ptr2))
    fmt.Println("Length of ptr3: ", len(ptr3))
  
}

输出

Length of ptr1:  6
Length of ptr2:  3
Length of ptr3:  4

例2 :

// Go program to illustrate how to find
// the length of the pointer to an array
package main
  
import (
    "fmt"
)
  
// Main function
func main() {
  
    // Creating an array
    arr := [6]int{200, 300,
        400, 500, 600, 700}
      
    var x int
  
    // Creating pointer
    var p [4]*int
  
    // Assigning the address
    for x = 0; x < len(p); x++ {
      
        p[x] = &arr[x]
    }
  
    // Displaying result
    for x = 0; x < len(p); x++ {
      
        fmt.Printf("Value of p[%d] = %d\n", x, *p[x])
    }
  
    // Finding length
    // Using len() function
    fmt.Println("Length of arr: ", len(arr))
    fmt.Println("Length of p: ", len(p))
}

输出

Value of p[0] = 200
Value of p[1] = 300
Value of p[2] = 400
Value of p[3] = 500
Length of arr:  6
Length of p:  4

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程