首頁 > 後端開發 > 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學習者快速成長!