gpt4 book ai didi

pointers - 在方法中初始化一个 nil 指针结构

转载 作者:IT王子 更新时间:2023-10-29 01:33:53 27 4
gpt4 key购买 nike

我有一个名为 Article 的结构,它有一个名为 Image 的字段。默认情况下,Image 的值为 nil。由于 Image 应该只作为 Image.Id 保存到数据库,所以我使用了 bson.BSONGetterbson.BSONSetterjson.Marshaler 接口(interface)来伪造这种行为。

但是在内部可以使用 Image 作为 io.ReadWriteCloser 如果我用其他帮助程序将文件加载到它上面。

package main

import (
"io"
"fmt"

"gopkg.in/mgo.v2"
)

type Article struct {
Name string
Image *Image
}

type Image struct {
Id interface{}

io.ReadWriteCloser
}

func (i *Image) SetBSON(r bson.Raw) error {
i = &Image{}

return r.Marshal(i.Id)
}

func (i *Image) GetBSON() (interface{}, error) {
return i.Id
}

func (i *Image) MarshalJSON() ([]byte, error) {
return json.Marshal(i.Id)
}

Playground

现在这种方法的问题是无法在 Image.SetBSON 中初始化 Image 因为 Imagenil

最佳答案

接收者是 passed by value ,包括指针接收器:它是一个副本,更改其值不会更改调用该方法的初始指针接收器。

参见“Why are receivers pass by value in Go?”。

函数 Setup 返回一个新的 *Foo 会更好:play.golang.org

func SetUp() *Foo {
return &Foo{"Hello World"}
}

func main() {
var f *Foo
f = SetUp()
}

输出:

Foo: <nil>
Foo: &{Bar:Hello World}

twotwotwo指向更好的约定 in the comments , 即创建一个包函数 foo.New(),如 sha512.New() .
但是在这里,您的 Setup() 函数可能不仅仅是创建一个 *Foo

关于pointers - 在方法中初始化一个 nil 指针结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25520485/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com