如何根据一个类型将其转换为新类型?

huangapple go评论65阅读模式
英文:

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

问题

我创建了一个新的类型,以满足我的应用程序需求的自定义方法。

type Content html.Node

我知道可以通过以下方式从类型为Contentcontent变量派生出一个html.Node

node := html.Node(content)

但是,如果有一个类型为html.Node的变量,我该如何转换为Content类型?

我发现可以通过以下方式实现...

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

content := Content(node)

...但是这样做不起作用,会给我报错:

无法将类型为*html.Node的变量转换为Content类型

英文:

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 ?

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

答案1

得分: 1

如果节点是html.Node,使用以下代码:

c := Content(node)

如果节点是*html.Node,使用以下代码:

c := (*Content)(node)

请注意,根据上面链接的规范:"如果类型以运算符*开头...必要时必须加括号以避免歧义。"


如果你想要Content而不是*Content,那么你需要在转换之前或之后取消引用指针,例如:

c := Content(*node) // 在转换之前取消引用
// 或者
c := *(*Content)(node) // 在转换之后取消引用

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

英文:

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

huangapple
  • 本文由 发表于 2023年3月8日 04:14:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/75666763.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定