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
That’s it!
Related posts

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.