While I had to point some data to a struct, I just got confused on what is Difference between []*Users
and *[]Users
in golang struct
If I have following struct -
type Users struct {
ID int
Name string
}
The difference is quite large:
*[]Users
would be a pointer to a slice of Users
. Ex:
package main
import (
"fmt"
)
type Users struct {
ID int
Name string
}
var (
userList []Users
)
func main(){
//Make the slice of Users
userList = []Users{Users{ID: 43215, Name: "Billy"}}
//Then pass the slice as a reference to some function
myFunc(&userList);
fmt.Println(userList) // Outputs: [{1337 Bobby}]
}
//Now the function gets a pointer *[]Users that when changed, will affect the global variable "userList"
func myFunc(input *[]Users){
*input = []Users{Users{ID: 1337, Name: "Bobby"}}
}
On the contrary, []*Users
would be a slice of pointers to Users
. Ex:
package main
import (
"fmt"
)
type Users struct {
ID int
Name string
}
var (
user1 Users
user2 Users
)
func main(){
//Make a couple Users:
user1 = Users{ID: 43215, Name: "Billy"}
user2 = Users{ID: 84632, Name: "Bobby"}
//Then make a list of pointers to those Users:
var userList []*Users = []*Users{&user1, &user2}
//Now you can change an individual Users in that list.
//This changes the variable user2:
*userList[1] = Users{ID:1337, Name: "Larry"}
fmt.Println(user1) // Outputs: {43215 Billy}
fmt.Println(user2) // Outputs: {1337 Larry}
}
Both use pointers, but in completely different ways. Mess around with both of these snippets for yourself at Golang Playground and read through this to get a better understanding.