Answer the question
In order to leave comments, you need to log in
Why do we need a structure pointer in a slice?
Hello. There is an example:
type Player struct {
Id int64
Name string
}
var players[] *Player
var players2[] Player
func main() {
players = append(players, &Player{Id: 1, Name: "Bob"})
players2 = append(players2, Player{Id: 1, Name: "Bob"})
fmt.Println(players)
fmt.Println(players2)
//...
}
Answer the question
In order to leave comments, you need to log in
It really depends on how you will use the data.
For example, if you pass players to all functions
someFunc1(players)
someFunc2(players)
someFunc3(players)
func main() {
var players[] *Player
players = append(players, &Player{Id: 1, Name: "Bob"})
...
players = append(players, &Player{Id: 100, Name: "Bob"})
for i := range players {
someFunc1(players[i])
someFunc2(players[i])
someFunc3(players[i])
someFunc4(players[i])
// или одна из someFunc вызывает еще какие то функции и передаёт players туда
}
}
A pointer is a data type that indicates where an object is stored in memory.
If you pass a structure to a function rather than a pointer to it (let's take Player as an example), then in fact a copy of this structure is created.
If you pass the address of the structure (&Player) to the function, then the changes that occur in the function will change the object that was originally passed.
func EditPlayer(p Player) {
p.Name = "John"
}
func EditOriginalPlayer(p *Player) {
p.Name = "John"
}
func main() {
player := Player{Name: "Bob"}
EditPlayer(player)
fmt.Print(player.Name)//"Bob" Имя не изменяется т.к. передаётся копия
EditOriginalPlayer(&player)
fmt.Print(player.Name)//"John" Имя изменилось т.к. передаётся адрес структуры т.е. "оригинал"
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question