Dire che voglio passare un puntatore a una funzione e modificare il valore di una struttura a cui punta il puntatore. Io normalmente fare questo dereferenziazione il puntatore:Ottenere valori diversi passando i puntatori a una funzione in Go
type Test struct { Value int}
func main() {
var i Test = Test {2}
var p *Test = &i
f(p)
println(i.Value) // 4
}
func f(p *Test) {
*p = Test{4}
}
La mia domanda è: perché questo codice non cambia il valore
type Test struct { Value int}
func main() {
var i Test = Test {2}
var p *Test = &i
f(p)
println(i.Value) // 2
}
func f(p *Test) {
// ?
p = &Test{4}
}
mentre questo si fa:
type Test struct { Value int}
func main() {
var i Test = Test {2}
var p *Test = &i
f(p)
println(i.Value) // 4
}
func f(p *Test) {
p.Value = 4
}