go – How to create object for a struct in golang-ThrowExceptions

Exception or error:

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.

How to solve:

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)}

Answer´╝Ü

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
}

Leave a Reply

Your email address will not be published. Required fields are marked *