How to Find the Length of the Pointer in Golang

In Go, pointers store a value’s memory address, and pointers don’t have a length. However, you can find the length of the value that a pointer points to if it’s a type that has a length, such as a slice or an array

To find the length of the element pointer points to in Go, use the len()” function. The “len()” function returns the total number of elements in the pointer to an array, even if the specified pointer is nil.

Syntax

func len(l Type) int

Parameters

l: It is the type of pointer

Example 1

package main

import (
  "fmt"
)

func main() {
  slice := []int{10, 20, 30, 40, 50}

  pointerToSlice := &slice

  length := len(*pointerToSlice)

  fmt.Println("Length of the slice:", length)
}

Output

Length of the slice: 5

Example 2

package main

import (
  "fmt"
)

// Struct to represent a Book
type Book struct {
  Title string
  Author string
  Pages int
}

// Struct to represent a Library
type Library struct {
  Books []*Book
}

// Function to add a book to the library
func (l *Library) AddBook(book *Book) {
  l.Books = append(l.Books, book)
}

// Function to list all books in the library
func (l *Library) ListBooks() {
  fmt.Println("Books in the Library:")
  for _, book := range l.Books {
    fmt.Println("Title:", book.Title, 
      "| Author:", book.Author, "| Pages:", book.Pages)
  }
}

// Function to find the total number of pages in the library
func (l *Library) TotalPages() int {
  totalPages := 0
  for _, book := range l.Books {
    totalPages += book.Pages
  }
  return totalPages
}

func main() {
  // Creating a Library
  library := &Library{}

  // Creating Books
  book1 := &Book{Title: "Go Programming", Author: "John Smith", Pages: 350}
  book2 := &Book{Title: "Artificial Intelligence", Author: "Jane Doe", Pages: 420}

  // Adding Books to the Library
  library.AddBook(book1)
  library.AddBook(book2)

  // Listing Books
  library.ListBooks()

  // Finding the Total Number of Pages
  totalPages := library.TotalPages()
  fmt.Println("Total Pages in the Library:", totalPages)
}

Output

How to Find the Length of the Pointer in Go

That’s it!

Related posts

Golang map length

Golang array length

Leave a Comment