指针解引用在Go中如何工作? [英] How does pointer dereferencing work in Go?

查看:100
本文介绍了指针解引用在Go中如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过 http://tour.golang.org/浏览golang教程,以及在示例29

I'm going through the golang tutorials at http://tour.golang.org/, and was experimenting a bit with some things in example 29

供您参考,原始示例复制在这里:

For your reference, the original example is copied here:

package main

import "fmt"

type Vertex struct {
    X, Y int
}

var (
    p = Vertex{1, 2}  // has type Vertex
    q = &Vertex{1, 2} // has type *Vertex
    r = Vertex{X: 1}  // Y:0 is implicit
    s = Vertex{}      // X:0 and Y:0
)

func main() {
    fmt.Println(p, q, r, s)
}

这是非常基础的,它显示了如何创建该新结构Vertex的实例.不过,示例28 显示了通过指向它的指针来操纵顶点,因此我对示例进行了一些修改并为输出感到惊讶.这是修改:

It's pretty basic, showing how to create instances of this fancy new struct, Vertex. Example 28, though, shows manipulating a vertex via a pointer to it, so I modified the example a bit and was surprised by the output. Here is the modification:

func main() {
    t := *q
    q.X = 4
    u := *q
    fmt.Println(p, q, r, s, t, u, t == u)
}

输出:

{1 2} &{4 2} {1 0} {0 0} {1 2} {4 2} false

让我惊讶的是t不是{4,2},这似乎意味着更改q.X会更改q指向的结构实例.来自C/C ++背景,这对我来说似乎是非常奇怪的行为.

The thing that surprised me is that t is not {4, 2}, which seems to mean that changing q.X changed the instance of the struct that q pointed to. Coming from a C/C++ background, this seems like extremely strange behavior to me.

那么,这里到底发生了什么?为什么使用q.X = 4更改顶点不会传播到t?

So, what's actually going on here? Why does using q.X = 4 to change the Vertex not propagate to t?

推荐答案

t := *q复制q指向的结构.

如果要观察从tq的变化,请坚持使用指针:

If you want to observe changes to q through t, then stick with a pointer:

func main() {
    t := q
    q.X = 4
    u := *q
    fmt.Println(p, q, r, s, t, u, *t == u)
}

这会产生您可能正在寻找的输出.

This produces the output you were probably looking for.

{1 2} &{4 2} {1 0} {0 0} &{4 2} {4 2} true

我不确定您觉得什么特别奇怪. C和C ++的行为方式相同.请考虑以下内容:

I'm not sure what seems extremely strange to you. C and C++ behave the same way. Consider the following:

#include <iostream>

struct Vertex
{
    int x;
    int y;
};

std::ostream& operator<<(std::ostream& out, const Vertex& v)
{
    out << "{ " << v.x << ", " << v.y << " }"; 
    return out;
}

int main()
{
    Vertex v = Vertex{1, 2};
    Vertex* q = &v;
    Vertex t = *q;
    q->x = 4;
    std::cout << "*q: " << *q << "\n";
    std::cout << " t: " << t << "\n";
}

此C ++代码的输出显示相同的行为:

The output of this C++ code shows the same behavior:

*q: { 4, 2 }  
t: { 1, 2 }

这篇关于指针解引用在Go中如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆