代码之家  ›  专栏  ›  技术社区  ›  Lambda killed App

[]*users和*[]users之间的差异golang struct

  •  -2
  • Lambda killed App  · 技术社区  · 7 年前

    当我不得不将一些数据指向一个结构时,我只是对 []*Users *[]Users 在戈朗结构中

    如果我有以下结构-

    type Users struct {
        ID int
        Name string
    }
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   hewiefreeman    7 年前

    差别很大:

    *[]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 将是指向 用户 . 前任:

    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 以便更好地理解。