While I had to point some data to a struct, I just got confused on the difference between []*Users
and *[]Users
in Golang struct
I have following struct
type Users struct {
ID int
Name string
}
Basic syntaxAmpersand (&) is used for obtaining the pointer of a variable while asterisks for dereferencing a pointer and defining type of a variable. We defined the language variable as a string and assigned it "golang" value.
In Go a pointer is represented using the * (asterisk) character followed by the type of the stored value. In the zero function xPtr is a pointer to an int . * is also used to “dereference” pointer variables. Dereferencing a pointer gives us access to the value the pointer points to.
"=" is assignment,just like other language. <- is a operator only work with channel,it means put or get a message from a channel. channel is an important concept in go,especially in concurrent programming.
& Operator gets the memory address where as * Opeartor holds the memory address of particular variable.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With