Perché i puntatori delle strutture non vengono stampati come puntatori di variabili? [chiuso]

3

Considera il seguente codice:

package main

import "fmt"

type Vertex struct {
    X, Y int
}

var (
    i = 10
    p = &i
    v = Vertex{1,2}
    q = &v
)

func main() {
    fmt.Println(p) // Outputs the memory location of the pointer
    fmt.Println(q) // Outputs the string &{1 2}
}

Perché la posizione di memoria del puntatore q non è stampata, come con p ?

    
posta kdnooij 23.09.2016 - 02:51
fonte

1 risposta

0

Questo perché go ti permette di usare i puntatori di tipo nello stesso modo in cui useresti una variabile regolare. Quindi se si passa un puntatore a un tipo, la funzione di ricezione funzionerà sulla copia originale. Se passi una copia dei dati, le modifiche non vengono applicate alla var originale.

Se la funzione richiede esplicitamente un puntatore piuttosto che passare un puntatore.

Ecco una modifica del tuo esempio che potrebbe chiarire come funziona.

package main

import "fmt"

type Vertex struct {
    X, Y int
}

var (
    i = 10
    p = &i
    v = Vertex{1, 2}
    q = &v
    t = &v.X
)

func main() {
    fmt.Println(p) // Outputs the memory location of the pointer
    fmt.Println(q) // Outputs the string &{1 2}
    fmt.Println(t)
    fmt.Println(&q)
}

Questa sezione da GO efficace

Pointers vs. Values

As we saw with ByteSize, methods can be defined for any named type (except
a pointer or an interface); the receiver does not have to be a
struct.

In the discussion of slices above, we wrote an Append function. We can
define it as a method on slices instead. To do this, we first
declare a named type to which we can bind the method, and then make
the receiver for the method a value of that type.

    type ByteSlice []byte

    func (slice ByteSlice) Append(data []byte) []byte {
    // Body exactly the same as the Append function defined above.
    }
This still requires the method to return the updated slice. We can
eliminate that clumsiness by redefining the method to take a pointer
to a ByteSlice as its receiver, so the method can overwrite the
caller's slice.

    func (p *ByteSlice) Append(data []byte) {
        slice := *p
        // Body as above, without the return.
        *p = slice
    }
In fact, we can do even better. If we modify our function so it looks like
a standard Write method, like this,

    func (p *ByteSlice) Write(data []byte) (n int, err error) {
        slice := *p
        // Again as above.
        *p = slice
        return len(data), nil
    }
then the type *ByteSlice satisfies the standard interface io.Writer, which
is handy. For instance, we can print into one.

    var b ByteSlice
    fmt.Fprintf(&b, "This hour has %d days\n", 7)
We pass the address of a ByteSlice because only *ByteSlice satisfies
io.Writer. The rule about pointers vs. values for receivers
is that value methods can be invoked on pointers and values, but
pointer methods can only be invoked on pointers.

This rule arises because pointer methods can modify the receiver; invoking
them on a value would cause the method to receive a copy of
the value, so any modifications would be discarded. The language
therefore disallows this mistake. There is a handy exception, though.
When the value is addressable, the language takes care of the common
case of invoking a pointer method on a value by inserting the address
operator automatically. In our example, the variable b is addressable,
so we can call its Write method with just b.Write. The compiler will
rewrite that to (&b).Write for us.

By the way, the idea of using Write on a slice of bytes is central to the
implementation of bytes.Buffer.
    
risposta data 05.10.2016 - 16:29
fonte

Leggi altre domande sui tag