gpt4 book ai didi

go - 在 Golang : how to rewrite return value's type 中为现有类型添加方法

转载 作者:IT王子 更新时间:2023-10-29 02:30:01 26 4
gpt4 key购买 nike

我想扩展现有的 goquery.Selection用我自己的方法输入并能够从包的选择器中使用它。我知道我无法“修补”现有方法——我需要创建一个新方法。但是我怎样才能强制现有的包函数使用我的新类型呢?我一般缺少什么,或者没有“好的”方法来做,最好使用函数?

package main

import (
"fmt"
"github.com/PuerkitoBio/goquery"
)

type customSelection goquery.Selection

func (s *customSelection) CustomMethod() int {
return 1
}

doc.Find("*").Each(func(i int, s *goquery.Selection) {
fmt.Println(s.CustomMethod()) // does not works since its still "goquery.Selection"
// how do I can get a result with customSelection type here?
})

最佳答案

由于不支持继承,最佳做法是将非本地类型嵌入到您自己的本地类型中,并对其进行扩展。

在设计模式术语中,它更广为人知的是组合: https://en.wikipedia.org/wiki/Composition_over_inheritance

关于go - 在 Golang : how to rewrite return value's type 中为现有类型添加方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31780876/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com