英文:
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”
接下来,输入类似以下格式的内容:接收者名称、类型、接口名称:
s ReceiverType package.InterfaceName
按下回车键,缺失的方法将会生成:
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"
Now type something like this: receiver name, type, interface name:
> s ReceiverType package.InterfaceName
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论