首頁 >後端開發 >Golang >如何將一種類型轉換為基於它的新類型?

如何將一種類型轉換為基於它的新類型?

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB轉載
2024-02-06 10:30:11564瀏覽

如何將一種類型轉換為基於它的新類型?

問題內容

我會建立一個新類型來新增特定於我的應用程式需求的自訂方法

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刪除