英文:
How to create object for a struct in golang
问题
File1.go
package abc
type ECA struct {
*CA
obcKey []byte
obcPriv, obcPub []byte
gRPCServer *grpc.Server
}
type ECAP struct {
eca *ECA
}
func (ecap *ECAP) ReadCACertificate(ctx context.Context, in *pb.Empty) (*pb.Cert, error) {
Trace.Println("gRPC ECAP:ReadCACertificate")
return &pb.Cert{Cert: ecap.eca.raw}, nil
}
File2.go
package main
import "abc"
var ecap abc.ECAP //creating instance
func main() {
err = ecap.ReadCACertificate(floo,floo)
}
我是一个新手。我想创建 ECAP 结构的实例并调用 ReadCACertificate 方法。目前我是这样创建的:"var ecap abc.ECAP //creating instance",但是它返回 "nil" 和空指针错误。
有人可以帮忙以高效的方式调用 ReadCACertificate 方法吗?
提前感谢。
英文:
File1.go
Package abc
type ECA struct {
*CA
obcKey []byte
obcPriv, obcPub []byte
gRPCServer *grpc.Server
}
type ECAP struct {
eca *ECA
}
func (ecap *ECAP) ReadCACertificate(ctx context.Context, in *pb.Empty) (*pb.Cert, error) {
Trace.Println("gRPC ECAP:ReadCACertificate")
return &pb.Cert{Cert: ecap.eca.raw}, nil
}
File2.go
package main
import "abc"
var ecap abc.ECAP //creating instance
func main() {
err = ecap.ReadCACertificate(floo,floo)
}
I am a newbie. I want to create instance of ECAP struct and call ReadCACertificate method. Right now i am creating like this "var ecap abc.ECAP //creating instance" which is giving "nil" and nil pointer error.
Can anyone help how to call the ReadCACertificate method in efficient way.
Thanks in advance.
答案1
得分: 1
你的示例不完整,但基本上你需要初始化你的结构体,因为它包含指针,而默认的指针值是nil。
var ecap := ECAP{new(ECA)}
你可以使用上述代码来初始化ecap
结构体,并将其指针字段ECA
初始化为nil
。
英文:
Your example is incomplete, but basically you need to initialize your struct, since it has pointers, and default pointer value is nil.
var ecap := ECAP{new(ECA)}
答案2
得分: 0
你需要从你的$GOPATH中导入第二个文件。你的函数返回两个值,而不仅仅是一个错误。
package main
import (
"$RELATIVE_PATH_FROM_GOPATH/abc"
)
var ecap := ECAP{new(ECA)} //初始化你的结构体,因为它有指针
func main() {
cert, err = ecap.ReadCACertificate(floo,floo)
}
# 文件1
type ECAP struct {
Eca *ECA //大写字母开头使字段可以被导出
}
英文:
You need to import the second file from your $GOPATH. And your function return 2 values, not just an error.
package main
import (
"$RELATIVE_PATH_FROM_GOPATH/abc"
)
var ecap := ECAP{new(ECA)} //initialize your struct, since it has pointers
func main() {
cert, err = ecap.ReadCACertificate(floo,floo)
}
File 1
type ECAP struct {
Eca *ECA //uppercase make field be exported
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论