How to print the slice of pointers to get the values instead of their address without slice iteration

Here is a code snippet :
https://play.golang.org/p/bQ5vWTlKZmV

package main

import (
	"fmt"
)

type user struct {
	userID int
	name   string
	email  string
}

func main() {
	var users []*user
	addUsers(users)
}

func addUsers(users []*user) {
	users = append(users, &user{userID: 1, name: "cooluser1", email: "cool.user1@gmail.com"})
	users = append(users, &user{userID: 2, name: "cooluser2", email: "cool.user2@gmail.com"})
	printUsers(users)
	printEachUser(users)

}

func printUsers(users []*user) {
	fmt.Printf("users at slice %v \n", users)
}

func printEachUser(users []*user) {
	for index, u := range users {
		fmt.Printf("user at user[%d] is : %v \n", index, *u)
	}
}

At above code, if I am printing the slice directly by fmt.printf , I get only the address of the values instead of actual value itself.
output : users at slice [0x442260 0x442280]
To read to the values always, i have to callfunc like printEachUser to iterate the slice and get the appropriate value .
output:
user at user[0] is : {1 cooluser1 cool.user1@gmail.com}
user at user[1] is : {2 cooluser2 cool.user2@gmail.com}
Is there any way, we can read the values inside the slice of pointers using fmt.printf and get value directly like below ? :
users at slice [&{1 cooluser1 cool.user1@gmail.com} , &{2 cooluser2 cool.user2@gmail.com}]

Implement the fmt.Stringer or fmt.GoStringer interfaces.

1 Like

Thank You :smile:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.