简体   繁体   English

golang中类型不一致,无法使用<type>作为*类型</type>

[英]Inconsistent type in golang, cannot use <Type> as *Type

Hello I have the next code in Golang:你好,我在 Golang 中有下一个代码:

func createPDF(count int)   {
    pdfFile := pdf.NewMaroto(consts.Portrait, consts.A4)
    pdfFile.SetPageMargins(10, 15, 10)
    writeGroups(pdfFile)
}

func  writeGroups(pdf *pdf.Maroto) {
    //Do something
}

If I send it as (&pdfFile) I'm not able to use its methods, I'm just seeing:如果我将它作为 (&pdfFile) 发送,我将无法使用它的方法,我只是看到:

在此处输入图像描述

I would like to pass this pdf variable as a pointer to the writeGroups method and I'm getting a Cannot use type (Maroto) as type * pdf.Maroto in Golang.我想将此 pdf 变量作为指向 writeGroups 方法的指针传递,并且我在 Golang 中得到了 Cannot use type (Maroto) as type * pdf.Maroto。 I'm new in the language, is that possible to do.我是这门语言的新手,有可能做到吗? What the issue means?问题是什么意思?

Thanks谢谢

Assuming you are using https://github.com/johnfercher/maroto pdf.Maroto is an interface and you can pass that into your function by reference without turning it into a pointer to an interface.假设您使用的是https://github.com/johnfercher/maroto pdf.Maroto是一个接口,您可以通过引用将其传递到您的 function 而无需将其转换为指向接口的指针。

So if you change your function to因此,如果您将 function 更改为

func  writeGroups(pdf pdf.Maroto) {
    //Do something
}

You should now be able to call the interface functions on pdf.Maroto.您现在应该能够调用 pdf.Maroto 上的接口函数。 Those functions definition are defined for pdf.Maroto and not *pdf.Maroto which is why you could not use them.这些函数定义是为 pdf.Maroto 而不是 *pdf.Maroto 定义的,这就是您不能使用它们的原因。

Alternatively if you are sure you need a pointer to the pdf.Maroto function, you could dereference the pointer then call the function you want.或者,如果您确定需要指向 pdf.Maroto function 的指针,您可以取消引用该指针,然后调用您想要的 function。

func  writeGroups(pdf *pdf.Maroto) {
    (*pdf).AddPage()
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM