在golang中复制指针值* a = * b [英] copy pointer values *a = *b in golang

查看:51
本文介绍了在golang中复制指针值* a = * b的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

type T struct {
    Id int
    Name string
}

func Copy(a *T, b *T) error {
    b.Id=5
    b.Name="gert"
    a = b
    return nil
}

a 仍然为空,我必须这样做

a is still empty, I have to do it like this

func Copy(a *T, b *T) error {
    b.Id = 5
    b.Name = "gert"
    a.Id = b.Id
    a.Name = b.Name
    return nil
}

现在 a b

为什么以及如何直接将 * b 复制到 * a ?

Why and how can I copy *b to *a directly?

推荐答案

第一个示例几乎是正确的.您将指针传递给两个对象.您将这些指针放在变量A和B中.但是A和B是局部变量,因此当您说 a = b 时,您只是在说忘记A(局部)中的内容".该程序的其余部分仍然具有指向这两个原始对象的指针.

Your first example is almost right. You pass in pointers to two objects. You put those pointers into variables A and B. But A and B are local variables, so when you say a=b you are merely saying "forget what was in A (locally)". The rest of the program still has pointers to those two original objects.

如果要将B的数据结构复制到A的数据结构,请执行以下操作:

If you want to copy the data structure at B into the data structure at A, do this instead:

*a = *b;

正如dmikalova在下面的注释中指出的那样,这仅复制结构-而不复制该结构指向的任何数据.如果您的结构具有指针,则指向的数据现在将被两个副本共享(因为它仅复制了指针).

As dmikalova pointed out in the comments below, this merely copies the structs -- but not any data the struct points to. If your struct has a pointer, the data it points to is now shared by the two copies (because it only copied the pointer).

从技术上讲,字符串始终是指针,因此永远不会将其作为结构的一部分进行复制.但是,因为字符串是不可变的(并且Go具有垃圾回收功能),所以字符串感觉"就像它们是您的结构的一部分,并且您不必担心神奇地保存的低级字符串共享无需思考就可以记忆.

Technically, strings are always pointers, so they are never copied as part of your struct. But because strings are immutable (and Go has Garbage Collection), strings "feel" like they are part of your struct, and you don't have to worry about the low-level string sharing that magically saves you memory without you having to think about it.

这篇关于在golang中复制指针值* a = * b的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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