Настройка sublime text 3 для golang
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Open with Desktop
- View raw
- Copy raw contents Copy raw contents
Copy raw contents
Copy raw contents
Sublime for Go (golang), setup properly
This setup assumes C:\GoPath as your GOPATH. Changes any occurrences of this string into your GOPATH if you chose otherwise.
Setup environment variables:
Hit Windows+S , type in environment variables and start Edit the system environment variables .
Go to the Advanced tab, click the Environment variables (lower part of the window).
Under System variables :
- set GOPATH to value C:\GoPath .
- modify Path and append the value ;C:\GoPath\bin (separate the previous path with the ; )
- set GOROOT to value C:\Go .
If you're going to use Git Bash , dump this in your ~/.profile ( %USERPROFILE%/.profile under Windows). Both Mac OS X and Windows should work with that configuration:
Make sure you have Package Control installed.
Install Sublime plugins:
Hit Control+Shift+P (opens the Palette) and type in: install pack .. you should see Package Control: Install Package in the list. If you don't see that, install Package Control above.
If Package Control: Install Package is shown, hit to pop the next box. Type in GoSublime and hit enter. It will install GoSublime
Hit Control+Shift+P , type in package install , hit and type in GoGuru . Hit again to install GoGuru.
Hit Control+Shift+P , type in package install , hit and type in Godef . Hit again to install Godef.
Hit Control+Shift+P , type in package install , hit and type in SublimeLinter . Hit again to install SublimeLinter 3.
Hit Control+Shift+P , type in package install , hit and type in SublimeLinter golint . Hit again to install SublimeLinter-contrib-golint.
Hit Control+Shift+P , type in package install , hit and type in SublimeLinter gotype . Hit again to install SublimeLinter-contrib-gotype. WARN: gotype currently blocks other linters, so you can either not install it, or disable it through the SublimeLinter menu.
Hit Control+Shift+P , type in package install , hit and type in SublimeLinter govet . Hit again to install SublimeLinter-contrib-govet.
Install some go command line tools:
(GoCode is integrated into GoSublime.. won't use an external version)
Configuring Sublime Text 3's plugins:
- golint and gotype are enabled automatically, check the Palette under SublimeLinter for more options. One notable function is SublimeLinter: Show all errors .. discover the keyboard shortcut in the Palette and memorize it.
Restart Sublime Text 3
If you have any issues, please open an issue on this repo.. I want that recipe to be flawless to onboard new Go developers on Sublime.
On Mac, you might have to restart your session, so that the ~/.profile changes are propagated to your running session. Otherwise, try starting Sublime from a terminal which has the GOPATH vars set.
Установить Sublime Text3
Установите официально предоставленный язык GoGolang build пакет
- Нажмите "Настройки"> Меню управления пакетами (ярлык MAC shift + command + p )
- Введите во всплывающем поле ввода install Выберите Управление пакетами: установить пакет
- Затем введите Golang build Выберите сборку Golang для установки
После установки нажмите Preferences Preferences> Package Setting > Golang Config > Настройка-Пользователь устанавливает некоторые параметры
Хорошо, теперь ты можешь попробовать
- Создать под рабочим пространством src оглавление:
mkdir -p $HOME/golang/workspace/src - Создать файл go hello.go
- Напишите следующее
иди и пройди тест
- -Нажмите «Настройки»> Меню управления пакетами (ярлык MAC shift + command + p )
- Введите во всплывающем окне go get , Нажмите Go: получить
- Результат: go get test success! Докажите, что вы можете использовать go get
запустить, установить, начать сборку, очистить и другие тесты
- Щелкните Toos> Построить с помощью (сочетание клавиш Shift + Command + b на Mac)
Programming with Go
A great starting point is the Introduction to Programming in Go book by Caleb Doxsey, and the JustForFunc: Programming in Go channel on YouTube.
Все настроено
Нажмите Ctrl + B, чтобы открыть окно компиляции, и введите go run ./main.go, чтобы запустить текущий файл.
Создайте собственную IDE для разработки языка Go
Хорошо, давайте не будем говорить слишком много ерунды, давайте приступим к созданию мощной IDE для разработки языка Go. Насколько она мощная? Убедитесь в этом сами:
- Поддержка автоматической настройки GOPATH
- Поддержка простая go run
- ожидать go get
- ожидать go install
- Конечно, также поддерживает "кросс-компиляцию"
- А также поддерживает go test go clean
Используйте Sublime text 3, чтобы создать небольшую, но мощную IDE для разработки языка Go
Недавно я изучал язык GO и искал в Интернете языковую IDE GO. Я обнаружил, что в настоящее время язык GO не имеет профессиональной IDE, которая реализуется различными плагинами. Из-за характеристик go:
- Необходимо установить во время разработки GOPATH
- Используйте сторонние пакеты для использования go get
- Используйте при беге go run
- Упакован для использования go install
- Также настройте при кросс-компиляции GOARCH GOOS go build
Я пробовал инструменты, которыми поделились многие друзья, не просты в использовании, я пробовал JetbrainsGoland Early build version, Обнаружено много ошибок, кросс-компиляции нет, не удалось go get , Не отвечает потребностям разработки, упаковки и распространения, но подсказки кода Goland по-прежнему очень хороши, и я надеюсь, что официальная версия может стать лучше в будущем.
Code linting
For linting of source code I'm using the SublimeLinter plugin. This plugin isn't a linter itself, but provides a framework for running linters and displaying error messages. You can install it like so:
- Open command palette by pressing Ctrl+Shift+P .
- Run the Package Control: Install Package command.
- Type SublimeLinter and hit Enter to install the package.
The next step is to install an actual linter. I'm using gometalinter, which acts as a wrapper around a bunch of different linters and picks up more potential problems and inefficiencies than using go vet and golint alone. You can install it with the commands:
Once that's done, you'll need to install the SublimeLinter-contrib-gometalinter plugin. This acts as the bridge between SublimeLinter and gometalinter.
- Open command palette by pressing Ctrl+Shift+P .
- Run the Package Control: Install Package command.
- Type SublimeLinter-contrib-gometalinter and hit Enter to install the package.
By default the linter will run in the background as you type, and errors will be shown in the Sublime Text status bar at the bottom of the screen. But I've found suits me more to only lint when saving a file and to display all errors at once in a panel. If you want to do the same, go to Preferences > Package Settings > SublimeLinter > Settings and add the following settings to the SublimeLinter Settings - User file:
I should mention that the SublimeLinter-contrib-gometalinter plugin only executes the 'fast' linters included in gometalinter . You can see exactly which ones are run by checking the source code.
Automatic formatting
For automatic formatting of .go files I've been using the Gofmt plugin. You can install it as follows:
- Open the Sublime Text command palette by pressing Ctrl+Shift+P .
- Run the Package Control: Install Package command.
- Type Gofmt and hit Enter to install the package.
By default this will run go fmt -s -e on the current file each time it is saved.
I've customised this further to use the goimports tool. If you're not already familiar with goimports , it runs go fmt and fixes your import lines — adding missing packages and removing unreferenced ones as necessary.
To set this up you'll need to install goimports and make sure it's available on your system path:
When that's installed, you'll then need to change the Gofmt plugin settings in Sublime Text by opening Preferences > Package Settings > Gofmt > Settings - User and adding the following configuration settings:
(You'll probably need to restart Sublime Text for this to take effect.)
Each time you now save a .go file, you'll find that it gets automatically formatted and the import packages are updated. No more "imported and not used" errors!
Настроить переменные среды
Установить пакет управления
Package control Это плагин для управления возвышенным текстом. Поскольку возвышенный текст поставляется в среде Python, управление пакетами может напрямую использовать следующие скрипты PythonАвтоматическая установка(Рекомендуется зайти на официальный сайт, чтобы найти скрипт, чтобы не обновить скрипт и не установить):
Для удобства просмотра моя точка с запятой в скрипте ; В конце добавляется разрыв строки, но это не влияет на использование.
Официальный адрес установкиPackage control installation, Вы увидите приведенный выше сценарий после входа.
Конечно, управление пакетами также имеетРучная установкапуть:
Чтобы автоматическая установка вступила в силу, также необходимо перезапустить.
Code navigation
To help with navigating code I use the guru tool, which you can install with the following command:
To integrate this with Sublime Text you'll also need to install the GoGuru plugin like so:
- Open command palette by pressing Ctrl+Shift+P .
- Run the Package Control: Install Package command.
- Type GoGuru and hit Enter to install the package.
- GoGuru: callees – Show possible targets of selected function call
- GoGuru: callers – Show possible callers of selected function
- GoGuru: callstack – Show path from callgraph root to selected function
- GoGuru: definition – Show declaration of selected identifier
- GoGuru: describe – Describe selected syntax: definition, methods, etc
- GoGuru: freevars – Show free variables of selection
- GoGuru: implements – Show 'implements' relation for selected type or method
- GoGuru: jump to definition – Open the file at the declaration of selected identifier
- GoGuru: peers – Show send/receive corresponding to selected channel op
- GoGuru: pointsto – Show variables the selected pointer may point to
- GoGuru: referrers – Show all refs to thing denoted by selected identifier
- GoGuru: what – Show basic information about the selected syntax node
- GoGuru: whicherrs – Show possible values of the selected error variable
You can find a detailed description these commands and their behaviour in this GoogleDoc.
I don't use the GoGuru plugin as often as the others, but when working on a unfamiliar codebase it definitely makes navigating code and building up a mental map of how things work easier. I find the GoGuru: jump to definition and GoGuru: callers commands particularly useful, and easier to use than grepping or running Ctrl+F on the repository.
As an illustration, here's a screenshot of running GoGuru: callers on the Sum function:
Используйте Sublime text 3, чтобы создать небольшую, но мощную IDE для разработки языка Go
Autocompletion
For autocompletion I'm using the gocode package, which provides a deamon for code completion. You can install it like so:
There isn't currently a gocode plugin available via Sublime Text package control (I might add one soon!)… but there is a plugin included in the subl3 directory within the gocode source itself.
You should be able to copy it into your Sublime Text Packages directory with the following command:
Note: If you're using MacOS then you will probably need to create a new Library/Application\ Support/Sublime\ Text\ 3/Packages/gocode directory and copy the plugin into this.
If you open the command palette and run Package Control: List Packages you should then see a gocode entry in the list.
By default Sublime Text will make autocomplete suggestions whenever a letter is pressed. But when working with Go I like also to display potential method names whenever I hit the . character. You can make that happen by going to Preferences > Settings and adding a new trigger in the Preferences.sublime-settings - User file:
You'll need to then restart Sublime Text for the settings to take effect. Once you have, you should have autocomplete working nicely and looking something like this:
Загрузите и установите Sublime Text 3
Sublime Text - это небольшой инструмент для редактирования текста, поддерживает windows, linux, macOS, нажмите на официальный адрес загрузкиsublime text.
После завершения загрузки установите его самостоятельно, здесь у вас не должно возникнуть проблем.
Useful Go Plugins
Popular Go plugins that work well with GoSublime are GoOracle, GoImports, and GoDoc.
You can install them with:
Read more here on how to configure these plugins to work with GoSublime.
Установить управление пакетами для Sublime Text 3
Откройте Sublime Text 3, нажмите Ctrl + `(обратная кавычка над клавишей Tab), введите следующее и нажмите Enter:
После установки перезапустите Sublime Text 3.
Установить Golang
Настройте среду разработки GoLang с помощью Sublime Text3 в Deepin Linux
Snippets
Sublime Text ships with a pretty good workflow for creating and using custom snippets. If you're not already familiar with this Jimmy Zhang has written a great in-depth guide that I recommend reading.
One thing that bugged me for a while was the built-in snippets for Go that Sublime Text ships with. In particular I didn't like the way that the main() snippet kept triggering whenever I wrote out "package main" .
If, like me, you want to edit these built-in snippets the easiest way is probably with the PackageResourceViewer plugin. You can install this as follows:
- Open command palette by pressing Ctrl+Shift+P .
- Run the Package Control: Install Package command.
- Type PackageResourceViewer and hit Enter to install the package.
Once installed you can open the command palette and run PackageResourceViewer: Open Resource which will list all packages on your system. If you navigate through Go > Snippets/ you should see a list of all the built-in snippets and you can open and edit them as you wish.
Hint: You can also use PackageResourceViewer to edit your own custom snippets without leaving SublimeText. If – for example – your custom snippets are saved under your Packages/User directory, you can open them by running PackageResourceViewer: Open Resource and navigating to the User folder.
If you enjoyed this article, you might like to check out my recommended tutorials list or check out my books Let's Go and Let's Go Further, which teach you everything you need to know about how to build professional production-ready web applications and APIs with Go.
Tooling integration
The official sublime-build plugin provides integrations so you can execute common go commands (like go run , go test and go get ) without leaving your editor.
You can install it like so:
- Open the Sublime Text command palette by pressing Ctrl+Shift+P .
- Run the Package Control: Install Package command.
- Type Golang Build and hit Enter to install the package.
After installation should see a bunch of new tools in your command palette. Their names are pretty self explanatory:
- Build With: Go
- Build With: Go - Clean
- Build With: Go - Install
- Build With: Go - Run
- Build With: Go - Test
- Build With: Go - Cross-Compile
- Go: Get
- Go: Open Terminal
When you run these commands they will open and execute in a panel within Sublime Text. As an example, here's a screenshot of output from the Build With: Go - Test command:
Update: An Up and Coming Go IDE
There is a new and cool looking Go IDE, Gogland, created by Jetbrains (the company behind the awesome IntelliJ and PyCharm). Check out the early build on their website.
For the past couple of years I've used Sublime Text as my primary code editor, along with the GoSublime plugin to provide some extra IDE-like features.
But I've recently swapped GoSublime for a more modular plugin setup and have been really happy with the way it's worked out. Although it took a while to configure, it's resulted in a coding environment that feels clearer to use and more streamlined than before.
- Tooling integration with the official sublime-build plugin.
- Automatic formatting with the Gofmt plugin and goimports.
- Code linting with the SublimeLinter plugin and gometalinter.
- Autocompletion with the gocode package.
- Code navigation with the GoGuru plugin.
- Snippet management with Sublime Text's inbuilt tool and the PackageResourceViewer plugin.
In this post I'm going to run through the process of setting these up. If you haven't come across these plugins before, I recommend giving them a try!
Установите GOPATH и GOROOT в Sublime Text 3
Откройте Sublime Text 3, меню“Preferences -> Package Settings -> GoSublime -> Settings-Default”, Откройте файл конфигурации GoSublime и измените информацию о настройках env:
. // опущено
"env": "GOROOT": "/usr/local/go",
"GOPATH": "~/golang"
>,
. // опущено
>
После настройки перезапустите Sublime Text 3.
Prerequisites
To work correctly some of these Sublime Text plugins need an explicit $GOPATH environment variable to be set. And if you're following along, you should also make sure that your workspace's bin directory is on your system path.
Accordingly my bash ~/.profile configuration includes these lines:
You'll also need to install Package Control, if you haven't already. In the latest version of Sublime Text the easiest way to do that by going to Tools > Install Package Control… .
экзамен
Установите GoSublime и улучшения боковой панели
Откройте Sublime Text 3, нажмите Ctrl + Shift + P, введите pcip во всплывающем окне и нажмите Enter. В это время Sublime Text 3 будет искать информацию об устанавливаемых пакетах по сети. Через некоторое время появится список пакетов. Войдите в GoSublime Нажмите Enter и дождитесь завершения установки GoSublime. После установки вам может быть предложено, что GOROOT GOPATH не установлен, независимо от этого, вы установите его позже (это не связано с GOPATH GOROOT, установленным в переменной системной среды).
снова нажмите Ctrl + Shift + P, введите pcip во всплывающем окне и нажмите Enter. Через некоторое время появится список пакетов, введите SidebarEnhancements, нажмите Enter и подождите Боковая панель Усовершенствования, которые необходимо установить.
Building and Running Go code
You can build, compile, and run your code directly from Sublime Text. Use CTRL+B or CTRL+9 like so:
Установить GoSublime
GoSublime - это интерактивный инструмент для сборки, который также очень удобен в использовании, в основном используется со сборкой Golang.
- Нажмите "Настройки"> Меню управления пакетами (ярлык MAC shift + command + p )
- Введите во всплывающем поле ввода install Выберите Управление пакетами: установить пакет
- Затем введите GoSublime Выберите GoSublime для установки
Используйте GoSublime
- Настройте GoSublime для автоматической установки GOPATH
- Настроить "use_gs_gopath": true , По умолчанию - false
Способ использования также:
- Щелкните Toos> Построить с помощью (сочетание клавиш Shift + Command + b на Mac)
- Выберите GoSublime, и появится интерактивный ввод
Здесь вы можете ввести команды, которые вы хотите использовать, получить, установить, создать и очистить.
I really love the Go programming language, it feels like a mix of the best of Java and Python put together. But I found that setting a Go development environment can be slightly tricky, mostly in figuring out how to set up the proper path variables.
Here, I provide a short guide on how to set up a Go development environment with Sublime Text 3 on Ubuntu/Linux. I hope it saves you (and my future-self) time when installing, updating, or re-installing the development environment.
Installing / Updating Go
If you’re updating a previously installed Go version, you must first delete the older one:
Note: some people use the Go version manager (GVM) to install and set up Go, a tool similar to NVM which I highly recommend for Node.js, but for Go I prefer to set up everything myself.
Next, set the PATH environment variables by adding the following to .bashrc :
Here I use home/alexeyza/go as my workspace (which is $HOME/go ), but feel free to change it according to your preference.
And, create your workspace:
Setting up Sublime Text
Sublime text is my editor of choice for many things, and I highly recommend it for Go. If you don’t have it installed, start by installing Sublime Text 3, and installing the Package Control plugin.
Install GoSublime through package control ( CTRL+Shift+P ). It’s a Sublime Text plugin that provides Go code completion and other IDE-like features.
Next, set up the PATH environment variables for Sublime Text. This setting has slightly changed over time (which is why you may find different instruction variations online), but my current set up works with the following settings in Preferences -> Package Settings -> GoSublime -> Settings-User .
Make sure the GOPATH matches the path configured earlier.
Now, save and restart Sublime Text. When you first restart Sublime Text after installing GoSublime, it may take a few seconds to install and set up MarGo.
Настроить рабочую среду
Установить git
Поскольку golang управляет удаленными пакетами через git, мы должны сначала установить git. Специальная ссылкаОфициальный веб-сайт。
Читайте также: