我有这段代码,它返回对切片的引用:
package main
import "fmt"
type V2BucketAccess struct {
BucketName string
AccessPolicy string
}
func main() {
result := MyFunc()
fmt.Print(*result)
}
func MyFunc() *[]V2BucketAccess {
parsedBucketsNames := []V2BucketAccess{}
mystuff1 := V2BucketAccess{
BucketName: "bucket-1",
AccessPolicy: "readwrite",
}
mystuff2 := V2BucketAccess{
BucketName: "bucket-2",
AccessPolicy: "read",
}
parsedBucketsNames = append(parsedBucketsNames, mystuff1, mystuff2)
return &parsedBucketsNames
}
我想用命名的返回值重写这个,我想出了这样的事情:
package main
import "fmt"
type V2BucketAccess struct {
BucketName string
AccessPolicy string
}
func main() {
result := MyFunc()
fmt.Print(*result)
}
func MyFunc() (parsedBucketsNames *[]V2BucketAccess) {
*parsedBucketsNames = []V2BucketAccess{}
mystuff1 := V2BucketAccess{
BucketName: "bucket-1",
AccessPolicy: "readwrite",
}
mystuff2 := V2BucketAccess{
BucketName: "bucket-2",
AccessPolicy: "read",
}
*parsedBucketsNames = append(*parsedBucketsNames, mystuff1, mystuff2)
return
}
但是,这会在 MyFunc() 函数的第一行生成分段违规。通过命名返回值执行此操作的正确方法是什么,或者这是不应使用命名返回值的情况之一?非常欢迎解释为什么我的解决方案会生成分段错误。
慕莱坞森
相关分类