Golang toString用于接口和结构实现

Golang toString用于接口和结构实现,go,Go,我有以下Go界面: type CodeProvider interface { code() string } 我已将CodeProviderImpl定义如下: type CodeProviderImpl struct { errorCode string } type JsonMessage struct { code CodeProvider } 这是使用“code()”方法对上述CodeProvider的实现: 我在我的另一个结构中使用codeProvider,如下

我有以下Go界面:

type CodeProvider interface {
    code() string

}
我已将CodeProviderImpl定义如下:

type CodeProviderImpl struct {
  errorCode string
}
type JsonMessage struct {
  code CodeProvider
}
这是使用“code()”方法对上述CodeProvider的实现:

我在我的另一个结构中使用codeProvider,如下所示:

type CodeProviderImpl struct {
  errorCode string
}
type JsonMessage struct {
  code CodeProvider
}
我在测试用例中执行此操作:

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

    jm := &JsonMessage{         
        code: codeProvider
    }
现在,当我使用以下代码执行测试时,我得到以下错误:

 log.Info("jm.code: ", string(jm.code))
无法将jm.code(类型CodeProvider)转换为类型string


如何打印jm.code的字符串表示形式?

您当前正在尝试将jm.code(一种CodeProvider结构类型)转换为一个不明显转换的字符串。如果试图获取CodeProvider结构的字符串表示形式,可以在fmt.Sprintf()中使用“%+v”标志

例如:

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

如果您要做的只是调用jm.code代码提供程序中的code函数来获取代码字符串,那么请使用jm.code.code()。

您需要调用
jm.code.code()
。我不确定您为什么希望为您调用
.code()
,也不确定您为什么要尝试将结构转换为字符串。您是否正在尝试实施?