Golang toString用于接口和结构实现

I have the following Go interface:

type CodeProvider interface {
    code() string

}

I have defined the CodeProviderImpl as following:

type CodeProviderImpl struct {
  errorCode string
}

This is the implementation for the above CodeProvider with "code()" method:

func (cp CodeProviderImpl) code()  string {
    log.Info("cp.errorCode: ", cp.errorCode)
    return cp.errorCode
}

I am using the codeProvider in my another Struct as following:

type JsonMessage struct {
  code CodeProvider
}

I do this in my test case:

codeProvider := &CodeProviderImpl { errorCode: "1"}

    jm := &JsonMessage{         
        code: codeProvider
    }

Now when I execute a test with the following code I get the following error:

 log.Info("jm.code: ", string(jm.code))

cannot convert jm.code (type CodeProvider) to type string

How to print the string representation of the jm.code?

You are currently attempting to convert jm.code, which is a CodeProvider struct type, to a string which isn't an obvious conversion. If you're attempting to get the string representation of the CodeProvider struct, you can use the "%+v" flag in fmt.Sprintf().

Example:

log.Info("jm.code: ", fmt.Sprintf("%+v", jm.code))

If all you're trying to do is call the code function in the jm.code code provider to get a code string, then use jm.code.code().