Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I convert a type to a new one based on it?

I create a new type to add custom methods specific for my app’s needs

type Content html.Node

I know I can derivate a html.Node from a content var of type Content doing this

node := html.Node(content)

But, having a var of type html.Node, how can I convert to a Content ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I discovered that doing the following …

ndoe, err := htmlquery.LoadURL(page.url)

content := Content(node) 

… cannot work. It gives me this error:

cannot convert doc (variable of type *html.Node) to type Content

>Solution :

https://go.dev/ref/spec#Conversions

If node is html.Node use:

c := Content(node)

If node is *html.Node use:

c := (*Content)(node)

Note from the above linked spec: "If the type starts with the operator * … it must be parenthesized when necessary to avoid ambiguity."


And if you want Content instead of *Content then you need to dereference the pointer, either before conversion or after, e.g.:

c := Content(*node) // dereference before conversion
// or
c := *(*Content)(node) // dereference after conversion

https://go.dev/play/p/zAu4H1R2D-L

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading