[] *用户和* []用户golang结构之间的区别

时间:2018-06-02 17:23:39

标签: pointers go struct

虽然我不得不将一些数据指向一个结构,但我对golang结构中[]*Users*[]Users之间的差异感到困惑

如果我有以下结构 -

type Users struct {
    ID int
    Name string
}

1 个答案:

答案 0 :(得分:0)

差异很大:

*[]Users将是指向Users切片的指针。例如:

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"}}
}

相反,[]*Users将成为Users指针的一部分。例如:

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}
}

两者都使用指针,但方式完全不同。在Golang Playground为您自己处理这两个片段并阅读this以便更好地理解。