如何在 VS Code for Go 中生成接口实现?

kol*_*pto 2 go visual-studio-code

在 VSCode 中,如何生成接口的实现?

比如说,我有这个界面:

type ServerInterface interface {
    // Set value for a device
    SetSomethingForDeviceById(ctx echo.Context, id int64) error
}
Run Code Online (Sandbox Code Playgroud)

如何生成实现它的方法?

kol*_*pto 9

VScode 支持使用 Go 扩展生成界面。

\n

操作方法如下:

\n

首先,从定义结构开始:

\n
type ApiServer struct {}\n
Run Code Online (Sandbox Code Playgroud)\n

现在,使用 Ctrl-Shift-P,找到此命令:“Gogenerateinterfacestubs”

\n

命令

\n

现在输入如下内容:接收者名称、类型、接口名称:

\n
\n

s ReceiverType 包.InterfaceName

\n
\n

输入

\n

按 Enter 键。生成缺少的方法:

\n
package api\n\nimport "github.com/labstack/echo/v4"\n\n// Set value for a device\nfunc (s ApiServer) SetSomethingForDeviceById(ctx echo.Context, id int64) error {\n    panic("not implemented")\n}\n
Run Code Online (Sandbox Code Playgroud)\n

@cl\xc3\xa9ment-jean 补充说:

\n
\n

该命令依赖于https://github.com/josharian/impl:您需要先安装它才能生成代码。

\n
\n

  • 您可能应该提到此命令取决于 [https://github.com/josharian/impl](https://github.com/josharian/impl),并且您需要先安装才能生成代码。 (3认同)