gpt4 book ai didi

pointers - Golang 中 []*Users 和 *[]Users 的区别?

转载 作者:数据小太阳 更新时间:2023-10-29 03:32:41 25 4
gpt4 key购买 nike

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

我有以下结构

type Users struct {
ID int
Name string
}

最佳答案

区别还是挺大的:

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

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以获得更好的理解。

关于pointers - Golang 中 []*Users 和 *[]Users 的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50659408/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com