首页 > 后端开发 > Golang > 正文

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

WBOY
发布: 2024-02-06 10:30:11
转载
436 人浏览过

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

问题内容

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

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

以上是如何将一种类型转换为基于它的新类型?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:stackoverflow.com
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!