简体   繁体   中英

Why does vscode delete golang source on save

why can't save these line of code in vscode with golang extension

package app

import (
  "fmt"
)

//this is just func
func TestingHello(){
  fmt.Println("Hissssss")
}

only the package app stays and remaining part got deleted on save in vscode.

Basically, your formatOnSave is on for go which is causing this problem.

To disable it, go to your Command Palette (Ctrl+Shift+P), type in "configure language specific settings", and look for Go.

You should now see a json file where you can add the following setting to it:

"editor.formatOnSave": false.

This is how the json file looks like if you just have on setting modified for go:

{
    "window.zoomLevel": 1,
    "[go]": {
        "editor.formatOnSave": false,
    }
}

config both editor.formatOnSave and editor.codeActionsOnSave in the settings.json:

"[go]": {

        "editor.formatOnSave": false,
        "editor.codeActionsOnSave": {
            "source.organizeImports": false
        },
    },
    "go.formatTool": "gofmt",

By default Format Tool is set to "goreturns" in settings.json, change it to "fmt":

{
    "go.formatTool": "gofmt"
}

Now you can comment the imports:

import (
    "fmt"
    // "reflect"
    // "math/rand"
)

I had a similar issue that was caused by not having the right case on method names.

In the following code import "fmt" would disappear.

package main

import "fmt"

func main() {
  fmt.println("hello world")
}

Solution I should be calling Println NOT println ! Note the uppercase P . Once changed goreturns adds the import instead of removing it.

That seems strange.
I can understand the import disappearing (as in issue 748 ) because of goreturns ( github.com/sqs/goreturns ) removing unused import. But that shouldn't apply in your case.

But if almost everything disappears, that means the file fails to be saved, and revert to its original content.
Maybe another process is keeping an handle on that file, preventing the save operation to proceed.

Ctrl+Shift+P --> Configure Language Specific Settings

       "editor.insertSpaces": false,
        "editor.formatOnSave": **false,**
        "editor.codeActionsOnSave": {
            "source.organizeImports": **false**
        }
    }
}

之所以出现这种情况,是因为你导入了什么,你没有在程序中使用它,所以Golang删除了不必要的依赖。

On VScode just press (CTRL + SHIFT + P ).

Then, Click on "Configure language-specific settings" and select GO lang.

Just paste code

"[go]": {
    "editor.insertSpaces": false,
    "editor.formatOnSave": true,
    "editor.codeActionsOnSave": {
        "source.organizeImports": true
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM