卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章64334本站已运行4115

如何将一种类型转换为基于它的新类型?

如何将一种类型转换为基于它的新类型?

问题内容

我创建一个新类型来添加特定于我的应用需求的自定义方法

type content html.node

我知道我可以从 content 类型的 content var 中派生出 html.node 执行此操作

node := html.node(content)

但是,有一个 html.node 类型的 var,如何转换为 content

我发现执行以下操作...

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

content := content(node)

...无法工作。它给了我这个错误:


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


正确答案


https://www.php.cn/link/b14fba037d119d307e3b6ceb2a9fbb31

如果节点是 html.node 使用:

c := content(node)

如果节点是 *html.node 使用:

c := (*content)(node)

上面链接规范的注释:“如果类型以运算符 * 开头...必要时必须将其放在括号中以避免歧义。”

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

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

https://www.php.cn/link/fb9d433088a21464e7d634c4e190b31a

卓越飞翔博客
上一篇: 在编组包含它的消息时,我可以重用现有的 protobuf 二进制文件吗?(protobuf3)
下一篇: 从 php 标准输入读取相当于什么?
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏