Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between []*Users and *[]Users in Golang?

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
}
like image 464
user3767643 Avatar asked Jun 02 '18 17:06

user3767643


People also ask

What is the difference between * and & In Golang?

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.

What does Star mean in Golang?

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.

What does <- mean in Golang?

"=" 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.

What is the use of & in Go?

& Operator gets the memory address where as * Opeartor holds the memory address of particular variable.


1 Answers

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.

like image 197
hewiefreeman Avatar answered Nov 14 '22 20:11

hewiefreeman