How to generate interface implementations in VS Code for Go?

huangapple go评论82阅读模式
英文:

How to generate interface implementations in VS Code for Go?

问题

在VSCode中,如何为接口生成实现代码?

比如,我有以下接口:

type ServerInterface interface {
	// 为设备设置值
	SetSomethingForDeviceById(ctx echo.Context, id int64) error
}

如何生成实现该接口的方法?

英文:

In VSCode, how do I generate the implementation for an interface?

Say, I have this interface:

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

How do I generate methods that implement it?

答案1

得分: 5

VScode支持使用Go扩展生成接口。

以下是操作步骤:

首先,你需要定义一个结构体:

type ApiServer struct {}

然后,使用Ctrl-Shift-P,找到命令:“Go generate interface stubs”

How to generate interface implementations in VS Code for Go?

接下来,输入类似以下格式的内容:接收者名称、类型、接口名称:

s ReceiverType package.InterfaceName

How to generate interface implementations in VS Code for Go?

按下回车键,缺失的方法将会生成:

package api

import "github.com/labstack/echo/v4"

// 为设备设置值
func (s ApiServer) SetSomethingForDeviceById(ctx echo.Context, id int64) error {
    panic("not implemented")
}

@clément-jean 补充道:

这个命令依赖于 https://github.com/josharian/impl:在生成代码之前,你需要先安装它。

英文:

VScode supports interface generation with the Go extension.

Here's how you do it:

First, you start with defining your struct:

type ApiServer struct {}

Now, use Ctrl-Shift-P, and find this command: "Go generate interface stubs"

How to generate interface implementations in VS Code for Go?

Now type something like this: receiver name, type, interface name:

> s ReceiverType package.InterfaceName

How to generate interface implementations in VS Code for Go?

Hit Enter. Missing methods are generated:

package api

import "github.com/labstack/echo/v4"

// Set value for a device
func (s ApiServer) SetSomethingForDeviceById(ctx echo.Context, id int64) error {
	panic("not implemented")
}

@clément-jean added that:

> this command depends on https://github.com/josharian/impl: you need to install it before being able to generate the code.

huangapple
  • 本文由 发表于 2023年2月28日 19:29:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/75591450.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定