Golang如何给import对象赋予新方法 (cannot define new methods on non-local type xxx)

举例:

假如我从某库engine中得到该库中定义的对象Request,我现在想赋予它新的方法,采用以下方式是不被允许的。

import (
	"github.com/slpslpslp/crawler/engine"
)

func (req *engine.Request) myselfMethod() {
//	do something
}

解决方法:

1. 新类型

type newRequest engine.Request

func (req newRequest) myselfMethod() {
	//	do something
}

2. 嵌入(推荐),见官方embedding方式

type newRequest struct {
	*engine.Request
}

func (req newRequest) myselfMethod() {
	//	do something
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章