search
HomeBackend DevelopmentGolangDetailed explanation of vim configuration of go language environment

Detailed explanation of vim configuration of go language environment

1. Environment preparation:

System environment description:

[root@docker golang]# cat /etc/redhat-release 
CentOS Linux release 7.2.1511 (Core) 
[root@docker golang]# uname -a
Linux docker 3.10.0-229.el7.x86_64 #1 SMP Fri Mar 6 11:36:42 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux
[root@docker golang]#

Prepare a go file for observing the configuration plug-in Changes in the process:

//hellogolang.go
package main
import "fmt"
func main() {
        fmt.Println("Hello Golang!")
}

2. Plug-in configuration path:

1. Vundle.vim:

#mkdir ~/.vim/bundle
#git clone https://github.com/gmarik/Vundle.vim.git ~/.vim/bundle/Vundle.vim

Configure vimrc: create~/ .vimrc file (if you do not have this file), add the configuration of Vundle.vim at the top of the file:

set nocompatible              " be iMproved, required
filetype off                  " required

" set the runtime path to include Vundle and initialize
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()

" let Vundle manage Vundle, required
Plugin 'gmarik/Vundle.vim'

" All of your Plugins must be added before the following line
call vundle#end()            " required
filetype plugin indent on    " required

At this time, Vim only has the Vundle.vim plug-in installed. Editing hellogolang.go is no different from editing an ordinary text file. Everything is still Vim’s default attributes

2. vim-go

Vim-go is currently the most widely used tool for building Golang. The vim plug-in for the development environment. Here I also use vim-go as the core and foundation to build the environment. vim-go is installed using the open source Vim plug-in manager. gmarik/Vundle.vim is currently the most recommended Vim plug-in manager, surpassing pathogen.

Here we use vundle as Vim’s plug-in management tool.

Edit ~/.vimrc, add a line between vundle#begin and vundle#end:

Plugin 'fatih/vim-go'

Execute in Vim: PluginInstall,

Vundle.vim A Vundle Installer Preview sub-window will open on the left, and a prompt will appear at the bottom of the window: "Processing 'fatih/vim-go'". After the installation is completed, the prompt message will change to "Done!".

At this time, we can see that there is an additional vim-go folder under .vim/bundle:

$ ls .vim/bundle/
vim-go/  Vundle.vim/

At this time, edit hellogolang.go again, the syntax Highlighting is now available, as is automatic format when saving (using $GOBIN/gofmt), but other advanced features, such as automatic import of missing packages and automatic completion, are still not available. We still need to continue to install some stuff.

3. Install go.tools Binaries

The vim-go installation instructions mention that all necessary binaries need to be installed first , such as gocode, godef, goimports, etc.

Through:GoInstallBinaries, these vim-go dependent binary tools will be automatically downloaded and installed under $GOBIN or $GOPATH/bin. (This tool requires git or hg and needs to be installed in your OS in advance.)

: The execution of GoInstallBinaries is interactive, you need to press Enter to confirm:

vim-go: gocode not found. Installing github.com/nsf/gocode to folder /home/tonybai/go/bin
vim-go: goimports not found. Installing code.google.com/p/go.tools/cmd/goimports to folder /home/tonybai/go/bin/
vim-go: godef not found. Installing code.google.com/p/rog-go/exp/cmd/godef to folder /home/tonybai/go/bin/
vim-go: oracle not found. Installing code.google.com/p/go.tools/cmd/oracle to folder /home/tonybai/go/bin/
vim-go: gorename not found. Installing code.google.com/p/go.tools/cmd/gorename to folder /home/tonybai/go/bin/
vim-go: golint not found. Installing github.com/golang/lint/golint to folder /home/tonybai/go/bin/
vim-go: errcheck not found. Installing github.com/kisielk/errcheck to folder /home/tonybai/go/bin/

But these codes Most of them are hosted on code.google.com, so due to well-known reasons, the automatic installation of vim-go is likely to fail. This requires you to download and install locally according to the source code address of each tool mentioned in the log above. . If you are unable to build a ladder, you can download the relevant package through http://gopm.io.

After installation, the new Binaries under $GOBIN are as follows:

-rwxr-xr-x  1 tonybai tonybai  5735552 11??  7 11:03 errcheck*
-rwxr-xr-x  1 tonybai tonybai  9951008 11??  7 10:33 gocode*
-rwxr-xr-x  1 tonybai tonybai  5742800 11??  7 11:07 godef*
-rwxr-xr-x  1 tonybai tonybai  4994120 11??  7 11:00 goimports*
-rwxr-xr-x  1 tonybai tonybai  5750152 11??  7 11:03 golint*
-rwxr-xr-x  1 tonybai tonybai  6381832 11??  7 11:01 gorename*
-rwxr-xr-x  1 tonybai tonybai  2954392 11??  7 10:38 gotags*
-rwxr-xr-x  1 tonybai tonybai  9222856 11??  7 11:01 oracle*

After installing these Binaries, let’s see which features are supported.

Edit hellogolang.go again:

- Start a new line and enter fmt., then ctrl x, ctrl o. Vim will pop up the completion prompt drop-down box, but it is not the kind of completion that follows in real time. Qi, this completion is provided by gocode.

– Enter a line of code: time.Sleep(time.Second), execute: GoImports, Vim will automatically import the time package.

– Move the cursor to the Sleep function, execute: GoDef or type gd in command mode, Vim will open the definition of the Sleep function in $GOROOT/src/time/sleep.go. Execution: b 1 returns to hellogolang.go.

– Execution: GoLint, run golint on the current Go source file.

– Execute: GoDoc to open the Go document corresponding to the symbol under the current cursor.

– Execute: GoVet, run go vet in the current directory on the current Go source file.

– Execute: GoRun, compile and run the current main package.

– Execute: GoBuild, compile the current package, which depends on your source files, GoBuild does not produce the result file.

– Execute: GoInstall to install the current package.

– Execute: GoTest, test the _test.go file under your current path.

– Execute: GoCoverage, create a test coverage result file, and open the browser to display the current package situation.

– Execute: GoErrCheck to check possible uncaught errors in the current package.

– Execute: GoFiles, display the list of source files corresponding to the current package.

– Execute: GoDeps, display the list of dependent packages of the current package.

– Execution: GoImplements, displays the interface list implemented by the current type.

– Execute: GoRename [to], replace the symbol under the current cursor with [to].

3. Other plug-ins

So far, we still have several features that have not been implemented, the key points are:

-Real-time following code supplement Qi
– Code Snippet support

1. Install YCM (Your Complete Me)

Add a line in ~/.vimrc:

Plugin 'Valloric /YouCompleteMe'

After saving and exiting, open ~/.vimrc and execute: PluginInstall

After installation, the following prompt bar prompts:

ycm_client_support.[so|pyd|dll] and ycm_core.[so|pyd|dll] not detected; you need to compile YCM before using it. Read the docs!

YCM is Modules written in C are used to optimize performance, so YCM's support library needs to be manually compiled. The steps are as follows:

sudo yum install build-essential cmake python-dev
cd ~/.vim/bundle/YouCompleteMe
./install.sh

Build (Compiling C is very slow, you need to wait patiently for a while) After OK, open hellogolang.go, and the real-time completion function will be available! Cool!

2. Install UltiSnips

Vim-go默认是用ultisnips引擎插件,但这个插件需要单独安装。同样,我们利用vundle来安装它,在~/.vimrc中添加一行:

Plugin 'SirVer/ultisnips'

保存,退出vim

打开vim,执行:PluginInstall

编辑hellogolang.go,按照go.snip中的说明,我们输入func后敲击tab键,我们发现期待的:

func name(params) type {
 }

并没有出现。反倒是YCM的下拉提示显示在那里让你选择。似乎是ultisnips和YCM的键组合冲突了。ultisnips官方说明也的确如 此。ultisnips默认是用Tab展开snippet的,而YCM中的Tab用来选择补齐项,我们可以通过设置来避免这些。

我们在.vimrc中添加如下setting:

" YCM settings
let g:ycm_key_list_select_completion = ['', '']
let g:ycm_key_list_previous_completion = ['']
let g:ycm_key_invoke_completion = &#39;<C-Space>&#39;

" UltiSnips setting
let g:UltiSnipsExpandTrigger="<tab>"
let g:UltiSnipsJumpForwardTrigger="<c-b>"
let g:UltiSnipsJumpBackwardTrigger="<c-z>"

这样让YCM通过回车和向下的箭头来做list item正向选择,通过向上箭头做反向选择。通过ctrl+space来原地触发补齐提示。

而ultisnips则是用tab做snippet展开,ctrl+b正向切换占位符,ctrl+z反向切换占位符。

四、.vimrc

前面讲到了vim-go有许多命令,在:xx模式下执行多显不便,于是你可以定义一些Mappings,比如:

 " set mapleader
  let mapleader = ","

  " vim-go custom mappings
  au FileType go nmap <Leader>s <Plug>(go-implements)
  au FileType go nmap <Leader>i <Plug>(go-info)
  au FileType go nmap <Leader>gd <Plug>(go-doc)
  au FileType go nmap <Leader>gv <Plug>(go-doc-vertical)
  au FileType go nmap <leader>r <Plug>(go-run)
  au FileType go nmap <leader>b <Plug>(go-build)
  au FileType go nmap <leader>t <Plug>(go-test)
  au FileType go nmap <leader>c <Plug>(go-coverage)
  au FileType go nmap <Leader>ds <Plug>(go-def-split)
  au FileType go nmap <Leader>dv <Plug>(go-def-vertical)
  au FileType go nmap <Leader>dt <Plug>(go-def-tab)
  au FileType go nmap <Leader>e <Plug>(go-rename)  

这样我们在命令模式下,输入+就是运行 当前main包,以此类推。

另外下面这个配置使得我们在save file时既可以格式化代码,又可以自动插入包导入语句(或删除不用的包导入语句)。

 " vim-go settings
let g:go_fmt_command = "goimports"

到这里,我们的Vim Golang开发环境就基本搭建好了。snippet+实时补齐让你Coding如飞!

五、.vimrc文件

下面是截至目前为止全量.vimrc文件的内容:

set nocompatible              " be iMproved, required
filetype off                  " required
colorscheme molokai

" set the runtime path to include Vundle and initialize
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()

" let Vundle manage Vundle, required
Plugin 'gmarik/Vundle.vim'
Plugin &#39;fatih/vim-go&#39;
Plugin 'Valloric/YouCompleteMe'

Plugin &#39;SirVer/ultisnips&#39;

" All of your Plugins must be added before the following line
call vundle#end()            " required
filetype plugin indent on    " required

" set mapleader
let mapleader = ","

" vim-go custom mappings
au FileType go nmap s (go-implements)
au FileType go nmap i (go-info)
au FileType go nmap gd (go-doc)
au FileType go nmap gv (go-doc-vertical)
au FileType go nmap r (go-run)
au FileType go nmap b (go-build)
au FileType go nmap t (go-test)
au FileType go nmap c (go-coverage)
au FileType go nmap ds (go-def-split)
au FileType go nmap dv (go-def-vertical)
au FileType go nmap dt (go-def-tab)
au FileType go nmap e (go-rename)

" vim-go settings
let g:go_fmt_command = "goimports"

" YCM settings
let g:ycm_key_list_select_completion = ['', '']
let g:ycm_key_list_previous_completion = ['', '']
let g:ycm_key_invoke_completion = ''

" UltiSnips settings
let g:UltiSnipsExpandTrigger=""
let g:UltiSnipsJumpForwardTrigger=""
let g:UltiSnipsJumpBackwardTrigger=""

更多golang知识请关注golang教程栏目。

The above is the detailed content of Detailed explanation of vim configuration of go language environment. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:博客园. If there is any infringement, please contact admin@php.cn delete
Golang vs. Python: The Pros and ConsGolang vs. Python: The Pros and ConsApr 21, 2025 am 12:17 AM

Golangisidealforbuildingscalablesystemsduetoitsefficiencyandconcurrency,whilePythonexcelsinquickscriptinganddataanalysisduetoitssimplicityandvastecosystem.Golang'sdesignencouragesclean,readablecodeanditsgoroutinesenableefficientconcurrentoperations,t

Golang and C  : Concurrency vs. Raw SpeedGolang and C : Concurrency vs. Raw SpeedApr 21, 2025 am 12:16 AM

Golang is better than C in concurrency, while C is better than Golang in raw speed. 1) Golang achieves efficient concurrency through goroutine and channel, which is suitable for handling a large number of concurrent tasks. 2)C Through compiler optimization and standard library, it provides high performance close to hardware, suitable for applications that require extreme optimization.

Why Use Golang? Benefits and Advantages ExplainedWhy Use Golang? Benefits and Advantages ExplainedApr 21, 2025 am 12:15 AM

Reasons for choosing Golang include: 1) high concurrency performance, 2) static type system, 3) garbage collection mechanism, 4) rich standard libraries and ecosystems, which make it an ideal choice for developing efficient and reliable software.

Golang vs. C  : Performance and Speed ComparisonGolang vs. C : Performance and Speed ComparisonApr 21, 2025 am 12:13 AM

Golang is suitable for rapid development and concurrent scenarios, and C is suitable for scenarios where extreme performance and low-level control are required. 1) Golang improves performance through garbage collection and concurrency mechanisms, and is suitable for high-concurrency Web service development. 2) C achieves the ultimate performance through manual memory management and compiler optimization, and is suitable for embedded system development.

Is Golang Faster Than C  ? Exploring the LimitsIs Golang Faster Than C ? Exploring the LimitsApr 20, 2025 am 12:19 AM

Golang performs better in compilation time and concurrent processing, while C has more advantages in running speed and memory management. 1.Golang has fast compilation speed and is suitable for rapid development. 2.C runs fast and is suitable for performance-critical applications. 3. Golang is simple and efficient in concurrent processing, suitable for concurrent programming. 4.C Manual memory management provides higher performance, but increases development complexity.

Golang: From Web Services to System ProgrammingGolang: From Web Services to System ProgrammingApr 20, 2025 am 12:18 AM

Golang's application in web services and system programming is mainly reflected in its simplicity, efficiency and concurrency. 1) In web services, Golang supports the creation of high-performance web applications and APIs through powerful HTTP libraries and concurrent processing capabilities. 2) In system programming, Golang uses features close to hardware and compatibility with C language to be suitable for operating system development and embedded systems.

Golang vs. C  : Benchmarks and Real-World PerformanceGolang vs. C : Benchmarks and Real-World PerformanceApr 20, 2025 am 12:18 AM

Golang and C have their own advantages and disadvantages in performance comparison: 1. Golang is suitable for high concurrency and rapid development, but garbage collection may affect performance; 2.C provides higher performance and hardware control, but has high development complexity. When making a choice, you need to consider project requirements and team skills in a comprehensive way.

Golang vs. Python: A Comparative AnalysisGolang vs. Python: A Comparative AnalysisApr 20, 2025 am 12:17 AM

Golang is suitable for high-performance and concurrent programming scenarios, while Python is suitable for rapid development and data processing. 1.Golang emphasizes simplicity and efficiency, and is suitable for back-end services and microservices. 2. Python is known for its concise syntax and rich libraries, suitable for data science and machine learning.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.