Pointers 解析指针

Pointers 解析指针,pointers,go,Pointers,Go,我对Golang(Golang)有点陌生,我被指针弄糊涂了。特别是,我似乎不知道如何解析或取消引用指针 以下是一个例子: package main import "fmt" type someStruct struct { propertyOne int propertyTwo map[string]interface{} } func NewSomeStruct() *someStruct { return &someStruct{ pro

我对Golang(Golang)有点陌生,我被指针弄糊涂了。特别是,我似乎不知道如何解析或取消引用指针

以下是一个例子:

package main

import "fmt"

type someStruct struct {
    propertyOne int
    propertyTwo map[string]interface{}
}

func NewSomeStruct() *someStruct {
    return &someStruct{
        propertyOne: 41,
    }
}

func aFunc(aStruct *someStruct) {
    aStruct.propertyOne = 987
}

func bFunc(aStructAsValue someStruct) {
    // I want to make sure that I do not change the struct passed into this function.
    aStructAsValue.propertyOne = 654
}

func main() {
    structInstance := NewSomeStruct()
    fmt.Println("My Struct:", structInstance)

    structInstance.propertyOne = 123 // I will NOT be able to do this if the struct was in another package.
    fmt.Println("Changed Struct:", structInstance)

    fmt.Println("Before aFunc:", structInstance)
    aFunc(structInstance)
    fmt.Println("After aFunc:", structInstance)

    // How can I resolve/dereference "structInstance" (type *someStruct) into
    // something of (type someStruct) so that I can pass it into bFunc?

    // &structInstance produces (type **someStruct)

    // Perhaps I'm using type assertion incorrectly?
    //bFunc(structInstance.(someStruct))
}
「运动场」守则

在上面的示例中,是否可以用“structInstance”调用“bFunc”?

如果“someStruct”结构在另一个包中,并且由于它未被报告,那么获取它的实例的唯一方法将是通过某个“New”函数(假设该函数将返回所有指针),那么这可能会是一个更大的问题


谢谢。

您在这里混淆了两个问题,这与指针无关,它与导出的变量有关

type someStruct struct {
    propertyOne int
    propertyTwo map[string]interface{}
}
someStruct
propertyOne
propertyTwo
不会导出(它们不会以大写字母开头),因此即使您从另一个包中使用
NewSomeStruct
,也无法访问字段

关于
bFunc
,您可以通过在变量名之前添加
*
来解除对指针的引用,例如:


我强烈建议大家仔细阅读,特别是这一部分

我理解,不以大写字母开头的名称不会导出到其包含包之外。事实上,这就是这个问题背后的主要动机——我不想让用户直接修改某个对象的底层结构,所以我将指针传回一个未报告的结构(但不知道如何将指针用于某个接受该结构的值[而非指针]的方法),感谢您指出“有效Go”一节,但是当页面显示如何执行“值->指针”时,我无法找到如何执行此问题中提到的“指针->值”转换。在进一步的实验后,我提出了另一个问题——带有指针接收器的方法似乎仍然可以通过值调用(假设该值被分配给某个变量)。在仍然能够将某个结构的实例存储在变量中的情况下,是否有任何方法可以防止这种情况发生?
bFunc(*structInstance)