VS Code easy to develop Go usage examples

Main records:

  • Use the Go plug-in
  • Common development use and shortcut key operation

Go plug-in operation mode:

  • An imperative operation:

    1. Select the content that you want to operate
    2. According to thectrl+shift+p, type:Go: related commands
    3. Press Enter, and enter the parameters required by the command. If there are no parameters, enter
  • Manual mouse point

    1. Select the content
    2. Right-click related operations and choose go commands, for exampleGo:Generate Unit Tests For Function
    3. Click the command and enter the parameters required for the command. It takes effect if there are no parameters

Automatically generate test cases

Command:Go:Generate Unit Tests For Function

The sample

Test code:

func Add(a, b int) int {
 return a + b 
}
Copy the code

After the command is executed, the test code is generated in the same directory as the function’s file:


func TestAdd(t *testing.T) {
 type args struct {
  a int
  b int
 }  tests := []struct {  name string  args args  want int } { // TODO: Add test cases.  }  for _, tt := range tests {  t.Run(tt.name, func(t *testing.T) {  ifgot := Add(tt.args.a, tt.args.b); got ! = tt.want { t.Errorf("Add() = %v, want %v", got, tt.want)  }  })  } } Copy the code

TODO: Add test cases. You need to fill out your own test cases

It is important to note that in the test function, t.log () does not output the contents of the terminal, so we need to add a -v argument:

  1. Search the extension store for those already installedgoPlug-in, click on the bottom right cornerSet the icon
  2. Select extension Settings
  3. findGo:Build FlagsTo add-vItem, as follows:
Insert a picture description here

This will output the contents of the log on the terminal when TestXXX is executed

Automatically generate structure instantiation

Command:Go:fill Struct

The sample

In the unit tests generated above, the struct instances are automatically generated where the test cases need to be added

  1. On a first{}The same is true for instantiations of any structure, such as:u := &User{}, the cursor in{}Then run the command.
  2. Then command operation can be

The generated code looks like this:

tests := []struct {
  name string
  args args
  want int
} { {  name: "". args: args{  a: 0. b: 0. },  want: 0. }  } Copy the code

One caveat, though:

Because tests is of type a []struct slice, you need to manually add a comma after the generated code, and press Save to format the code automatically

I use this a lot. I have Alt + F

Automatic implementation interface

Command:Go:Generate Interface Stubs

This command requires three parameters:

  • Method receiver parameter name eg:s
  • Method recipient name, which is the name of the implementation class, eg:*StudentYou can specify whether it is a value type or a reference type
  • For the name of the interface to implement, add the package name eg:code.Speaker

S *Student code.speaker

The sample

package code

type Speaker interface {
 // Speak speak action
 Speak()
}  type Student struct { }  // Speak speak action func (s *Student) Speak(a) {  panic("not implemented") // TODO: Implement } Copy the code

As you can see, comments are also generated to help.

Automatically add/remove tags

Add command:Go:Add Tags To Struct Fileds

Delete command:Go:Remove Tags From Struct Fileds

Select the field you want to generate the tag for, execute the command (add and delete fields are the same, need to select fields, only the selected fields will be executed)

The default is to generate only JSON tags, which can be customized. In setting.json, add the go.addTags setting

Example Settings:

 // Struct tag is set
  "go.addTags": {
    // Can be configured with multiple tag JSON, ORM
    "tags": "json,form".    // Options can be json=omitempty
 "options": "". "promptForTags": false. // snakecase: underline separated, camelcase: camel name  "transform": "camelcase"  }, Copy the code

I also use this a lot, set the shortcut Alt + A, delete not used, not set.

Quick package import

Command:Go:Add import

In general, packages are automatically introduced when code is written and intelligently prompted or saved. However, sometimes vscode will introduce the wrong package when introducing a package with the same name. This is mainly because there is a library with the same name in the local PKG ->mod directory, and vscode has no way of knowing which one it is.

At this time, we need to manually introduce, execute the command, and then enter the package name, select the enter you want from the display list, support fuzzy search

This is often used, and I have a shortcut key: Alt + I

Find the concrete implementation of the interface

  1. Mouse over the interface definition
  2. quickctrl+f12
  3. Or right click and select:Go to implementations

This operation occurs in two ways:

  • There is only one implementation, so jump directly to the implementation structure
  • If there are multiple implementations, a screen pops up with the implementation code on the left and a list of implementations on the right, both linked. Then select the implementation you want to see and double click to jump to it

refactoring

rename

  1. Select the field, method, interface name, and so on that you want to refactor
  2. According to theF2“, and then enter the name you want

This renames all references to the field, method, interface, and supports cross-file renaming

Field to extract

Command:Go:Extract to variable

Field extraction is mainly used to judge the scene with complex conditions. If the condition judgment is used in multiple places, it is best to extract it and extract it into a variable

Operation:

  • Select the content to extract
  • Execute the command
  • Enter the name of the variable to generate

Wait 1s to generate the code

Function to extract

Command:Go:Extract to function

Function extraction is mainly used in scenarios where logic is reusable. Pull out the same piece of logic into a function

Operation:

  • Select the content to extract
  • Execute the command
  • Enter the name of the function to generate

Wait 1s to generate the code

The sample

The original code:

func ExtractFuncTest(a, b, c int) {
 if a > 0 {
 }
 if b > 0 {
 }
 if c > 0 {  } } Copy the code

Select the inside of the logic, function after the extraction of the code:

func ExtractFuncTest(a, b, c int) {
 flag(a, b, c)
}

func flag(a int, b int, c int) {
 if a > 0 {  }  if b > 0 {  }  if c > 0 {  } } Copy the code

Third-party libraries are added to the current workspace

Generally vscode shows only the current project’s directory on the left side, not the imported third-party libraries. There is no External Libary directory like Goland

This function is not very useful, at present I can only import some go libraries, such as FMT, Errors library, third-party library is not available. To be solved

Set up Go related commands, right click to display commonly used commands

In the Settings. The json, input go. EditorContextMenuCommands, in fact, before the input letters will be smart tips, is generated after the enter configuration, as follows:

"go.editorContextMenuCommands": {
"toggleTestFile": true."addTags": false."removeTags": true."testAtCursor": true."testFile": true."testPackage": false."generateTestForFunction": true."generateTestForFile": false."generateTestForPackage": false."addImport": false."testCoverage": true."playground": true."debugTestAtCursor": true }, Copy the code

True indicates that VS Code is enabled. After setting, restart VS Code

Reference:

Do you really know how to use vscode-go?