go语言windows编程_如何在Windows 10上安装Go并设置本地编程环境


介绍 (Introduction)

Go is a programming language that was born out of frustration at Google. Developers continually had to pick a language that executed efficiently but took a long time to compile, or to pick a language that was easy to program but ran inefficiently in production. Go was designed to have all three available at the same time: fast compilation, ease of programming, and efficient execution in production.

Go是一种编程语言,它源于Google的无奈之举。 开发人员不断不得​​不选择一种执行效率高但编译时间长的语言,或者选择一种易于编程但在生产中运行效率低下的语言。 Go旨在同时提供所有三个功能:快速编译,易于编程以及在生产中高效执行。

While Go is a versatile programming language that can be used for many different programming projects, it’s particularly well suited for networking/distributed systems programs, and has earned a reputation as “the language of the cloud”. It focuses on helping the modern programmer do more with a strong set of tooling, removing debates over formatting by making the format part of the language specification, as well as making deployment easy by compiling to a single binary. Go is easy to learn, with a very small set of keywords, which makes it a great choice for beginners and experienced developers alike.

尽管Go是一种通用的编程语言,可以用于许多不同的编程项目,但它特别适合于网络/分布式系统程序,并赢得了“云语言”的美誉。 它着重于帮助现代程序员使用强大的工具集来做更多的事情,通过使格式成为语言规范的一部分来消除有关格式的争论,并通过编译为单个二进制文件使部署变得容易。 Go易于学习,只包含很少的关键字,对于初学者和经验丰富的开发人员而言,它都是不错的选择。

This tutorial will guide you through installing Go on your local Windows 10 machine and setting up a programming environment via the command line.

本教程将指导您在本地Windows 10计算机上安装Go并通过命令行设置编程环境。

先决条件 (Prerequisites)

You will need a Windows 10 machine with administrative access that is connected to the internet.

您将需要一台具有管理访问权限的Windows 10计算机,该计算机已连接到Internet。

步骤1 —打开和配置PowerShell (Step 1 — Opening and Configuring PowerShell)

You’ll be completing most of the installation and setup on a command-line interface, which is a non-graphical way to interact with your computer. That is, instead of clicking on buttons, you’ll be typing in text and receiving feedback from your computer through text as well. The command line, also known as a shell, can help you modify and automate many of the tasks you do on a computer every day, and is an essential tool for software developers.

您将在命令行界面上完成大多数安装和设置,这是与计算机交互的非图形方式。 也就是说,您将不用输入按钮,而是输入文本,并通过文本接收来自计算机的反馈。 命令行(也称为外壳程序 )可以帮助您修改和自动化每天在计算机上执行的许多任务,并且是软件开发人员的必备工具。

PowerShell is a program from Microsoft that provides a command-line shell interface. Administrative tasks are performed by running cmdlets, pronounced command-lets, which are specialized classes of the .NET software framework that can carry out operations. Open-sourced in August 2016, PowerShell is now available across platforms, for both Windows and UNIX systems (including Mac and Linux).

PowerShell是Microsoft提供的命令行外壳程序界面程序。 通过运行cmdlet (发音为command-let)来执行管理任务,这些命令.NET软件框架的专用类,可以执行操作。 PowerShell于2016年8月开源,现在可跨平台使用,适用于Windows和UNIX系统(包括Mac和Linux)。

To find Windows PowerShell, you can right-click on the Start menu icon on the lower left-hand corner of your screen. When the menu pops up, click on Search, and then type PowerShell into the search bar. When you are presented with options, right-click on Windows PowerShell from the Desktop app. For the purposes of this tutorial, select Run as Administrator. When you are prompted with a dialog box that asks Do you want to allow this app to make changes to your PC? click on Yes.

要找到Windows PowerShell,可以右键单击屏幕左下角的“ 开始”菜单图标。 弹出菜单时,单击“ 搜索” ,然后在搜索栏中键入PowerShell 。 当您看到选项时,请从“桌面”应用中右键单击Windows PowerShell 。 就本教程而言,选择以管理员身份运行 。 当系统提示您一个对话框,询问您是否要允许此应用程序对PC进行更改时? 单击

Once you do this, you’ll see a text-based interface that has a string of words that looks like this:


Switch out of the system folder by typing the following command:


  • cd ~


You’ll then be in a home directory such as PS C:\Users\sammy.

然后,您将位于主目录中,例如PS C:\Users\ sammy

To continue with the installation process, you must first set up permissions through PowerShell. Configured to run in the most secure mode by default, there are a few levels of permissions that you can set up as an administrator:

要继续安装过程,必须首先通过PowerShell设置权限。 默认情况下,配置为以最安全的模式运行,您可以将以下级别的权限设置为管理员:

  • Restricted is the default execution policy. Under this mode you will not be able to run scripts, and PowerShell will work only as an interactive shell.

    限制是默认执行策略。 在这种模式下,您将无法运行脚本,PowerShell将仅作为交互式外壳运行。

  • AllSigned will enable you to run all scripts and configuration files that are signed by a trusted publisher, meaning that you could potentially open your machine up to the risk of running malicious scripts that happen to be signed by a trusted publisher.


  • RemoteSigned will let you run scripts and configuration files downloaded from the internet signed by trusted publishers, again opening your machine up to vulnerabilities if these trusted scripts are actually malicious.


  • Unrestricted will run all scripts and configuration files downloaded from the internet as soon as you confirm that you understand that the file was downloaded from the internet. In this case no digital signature is required, so you could be opening your machine up to the risk of running unsigned and potentially malicious scripts downloaded from the internet.

    确认您了解文件是从Internet下载的后, Unrestricted将运行从Internet下载的所有脚本和配置文件。 在这种情况下,不需要数字签名,因此您可能会打开计算机,以运行从互联网下载的未签名和潜在恶意脚本的风险。

In this tutorial you will use the RemoteSigned execution policy to set the permissions for the current user. This will allow the PowerShell to accept trusted scripts without making the permissions as broad as they would be with an Unrestricted permission. Enter the following in PowerShell:

在本教程中,您将使用RemoteSigned执行策略来设置当前用户的权限。 这将使PowerShell能够接受可信脚本,而无需像使用Unrestricted权限那样广泛地设置权限。 在PowerShell中输入以下内容:

  • Set-ExecutionPolicy -Scope CurrentUser

    Set-ExecutionPolicy -Scope CurrentUser

PowerShell will then prompt you to provide an execution policy. Enter the following to use RemoteSigned:

然后,PowerShell将提示您提供执行策略。 输入以下内容以使用RemoteSigned

  • RemoteSigned


Once you press ENTER, you’ll be asked to confirm the change to the execution policy. Type the letter y to allow the changes to take effect. You can confirm that this worked by asking for the current permissions across the machine:

按下ENTER ,将要求您确认对执行策略的更改。 输入字母y以使更改生效。 您可以通过询问机器上的当前权限来确认是否可行:

  • Get-ExecutionPolicy -List


You should receive output that looks something like this:


Scope ExecutionPolicy ----- --------------- MachinePolicy Undefined UserPolicy Undefined Process Undefined CurrentUser RemoteSigned LocalMachine Undefined

This confirms that the current user can run trusted scripts downloaded from the internet. You can now move on to downloading the files we will need to set up our Go programming environment.

这确认当前用户可以运行从Internet下载的受信任脚本。 现在,您可以继续下载设置Go编程环境所需的文件。

第2步-安装Package Manager Chocolatey (Step 2 — Installing the Package Manager Chocolatey)

A package manager is a collection of software tools that work to automate installation processes. This includes the initial installation, upgrading and configuring of software, and removing software as needed. They keep software installations in a central location and can maintain all software packages on the system in formats that are commonly used.

程序包管理器是软件工具的集合,这些工具可以自动执行安装过程。 这包括软件的初始安装,升级和配置,以及根据需要删除软件。 它们将软件安装保持在中央位置,并可以以常用格式维护系统上的所有软件包。

Chocolatey is a command-line package manager built for Windows that works like apt-get does on Linux. Available in an open-source version, Chocolatey will help you quickly install applications and tools. You will be using it to download what you need for your development environment.

Chocolatey是为Windows构建的命令行程序包管理器,其工作方式类似于apt-get在Linux上的工作方式。 Chocolatey具有开源版本,可帮助您快速安装应用程序和工具。 您将使用它来下载开发环境所需的内容。

Before installing the script, read it to confirm that you are happy with the changes it will make to your machine. To do this, use the .NET scripting framework to download and display the Chocolatey script within the terminal window.

在安装脚本之前,请阅读该脚本以确认您对该脚本所做的更改感到满意。 为此,请使用.NET脚本框架在终端窗口中下载并显示Chocolatey脚本。

Start by creating a WebClient object called $script that shares internet connection settings with Internet Explorer:

首先创建一个名为$script的WebClient对象,该对象与Internet Explorer共享Internet连接设置:

  • $script = New-Object Net.WebClient

    $ script =新对象Net.WebClient

Take a look at the available options by piping the $script object with | to the Get-Member class:


  • $script | Get-Member

    $ script | 获得会员

This will return all members (properties and methods) of this WebClient object:


Snippet of Output
. . . DownloadFileAsync Method void DownloadFileAsync(uri address, string fileName), void DownloadFileAsync(ur... DownloadFileTaskAsync Method System.Threading.Tasks.Task DownloadFileTaskAsync(string address, string fileNa... DownloadString Method string DownloadString(string address), string DownloadString(uri address) #method we will use DownloadStringAsync Method void DownloadStringAsync(uri address), void DownloadStringAsync(uri address, Sy... DownloadStringTaskAsync Method System.Threading.Tasks.Task[string] DownloadStringTaskAsync(string address), Sy… . . .

Looking over the output, you can identify the DownloadString method used to display the script and signature in the PowerShell window. Use this method to inspect the script:

查看输出,可以确定用于在PowerShell窗口中显示脚本和签名的DownloadString方法。 使用此方法检查脚本:

  • $script.DownloadString("https://chocolatey.org/install.ps1")

    $ script.DownloadString(“ https://chocolatey.org/install.ps1”)

After inspecting the script, install Chocolatey by typing the following into PowerShell:


  • iwr https://chocolatey.org/install.ps1 -UseBasicParsing | iex

    iwr https://chocolatey.org/install.ps1 -UseBasicParsing | 进出口

The cmdlet iwr, or Invoke-WebRequest, allows you to extract data from the web. This will pass the script to iex, or the Invoke-Expression cmdlet, which will execute the contents of the script and run the installation for the Chocolatey package manager.

cmdlet iwrInvoke-WebRequest允许您从Web提取数据。 这会将脚本传递给iexInvoke-Expression cmdlet,后者将执行脚本的内容并为Chocolatey软件包管理器运行安装。

Allow PowerShell to install Chocolatey. Once it is fully installed, you can begin installing additional tools with the choco command.

允许PowerShell安装Chocolatey。 完全安装后,您可以使用choco命令开始安装其他工具。

If you need to upgrade Chocolatey at any time in the future, run the following command:


  • choco upgrade chocolatey


With the package manager installed, you can install the rest of what you need for the Go programming environment.


第3步-安装文本编辑器Nano(可选) (Step 3 — Installing the Text Editor Nano (Optional))

In this step, you are going to install nano, a text editor that uses a command-line interface. You can use nano to write programs directly within PowerShell. This is not a compulsory step, as you can also use a text editor with a graphical user interface such as Notepad. This tutorial recommends using nano, as it will help accustom you to using PowerShell.

在此步骤中,您将安装使用命令行界面的文本编辑器nano 。 您可以使用nano来直接在PowerShell中编写程序。 这不是强制性的步骤,因为您还可以将文本编辑器与图形用户界面(例如记事本)一起使用。 本教程建议使用nano,因为它将帮助您习惯使用PowerShell。

Use Chocolatey to install nano:


  • choco install -y nano

    choco安装-y nano

The -y flag automatically confirms that you want to run the script without being prompted for confirmation.


Once nano is installed, you can use the nano command to create new text files. You will use it later in this tutorial to write your first Go program.

安装nano之后,您可以使用nano命令创建新的文本文件。 在本教程的后面,您将使用它来编写您的第一个Go程序。

第4步-安装Go (Step 4 — Installing Go)

Just like you did with nano in the previous step, you will use Chocolatey to install Go:


  • choco install -y golang

    choco install -y golang

Note: Because go is such a small word, it has become common to use golang as a term for installing packages and when searching the internet for Go-related articles. The term Golang was born from the domain for Go, which is golang.org.

注意:因为go是一个很小的词,所以使用golang作为安装软件包的术语以及在Internet上搜索与Go有关的文章时已经很普遍。 术语Golang从域去,这是天生golang.org

PowerShell will now install Go, generating output within PowerShell during that process. Once the install is completed, you should see the following output:

PowerShell现在将安装Go,并在该过程中在PowerShell中生成输出。 安装完成后,您应该看到以下输出:

Environment Vars (like PATH) have changed. Close/reopen your shell to see the changes (or in powershell/cmd.exe just type `refreshenv`). The install of golang was successful. Software installed as 'msi', install location is likely default. Chocolatey installed 1/1 packages. See the log for details (C:\ProgramData\chocolatey\logs\chocolatey.log).

With the installation finished, you’ll now confirm that Go is installed. To see the changes, close and re-open PowerShell as an Administrator, then check the version of Go available on your local machine:

安装完成后,您现在将确认已安装Go。 要查看更改,请以管理员身份关闭并重新打开PowerShell,然后检查本地计算机上可用的Go版本:

  • go version


You’ll receive output similar to the following:


go version go1.12.1 windows/amd643.7.0

Once Go is installed, you can set up a workspace for your development projects.


第5步-创建您的Go工作区 (Step 5 — Creating Your Go Workspace)

Now that you have Chocolatey, nano, and Go installed, you can create your programming workspace.


The Go workspace will contain two directories at its root:


  • src: The directory that contains Go source files. A source file is a file that you write using the Go programming language. Source files are used by the Go compiler to create an executable binary file.

    src :包含Go源文件的目录。 源文件是您使用Go编程语言编写的文件。 Go编译器使用源文件来创建可执行的二进制文件。

  • bin: The directory that contains executables built and installed by the Go tools. Executables are binary files that run on your system and execute tasks. These are typically the programs compiled by your source code or another downloaded Go source code.

    bin :该目录包含由Go工具构建和安装的可执行文件。 可执行文件是在系统上运行并执行任务的二进制文件。 这些通常是由您的源代码或其他已下载的Go源代码编译的程序。

The src subdirectory may contain multiple version control repositories (such as Git, Mercurial, and Bazaar). You will see directories like github.com or golang.org when your program imports third party libraries. If you are using a code repository like github.com, you will also put your projects and source files under that directory. This allows for a canonical import of code in your project. Canonical imports are imports that reference a fully qualified package, such as github.com/digitalocean/godo.

src子目录可能包含多个版本控制存储库(例如GitMercurialBazaar )。 你会看到这样的目录github.comgolang.org当你的程序导入第三方库。 如果您使用的是github.com类的代码存储库,还将把项目和源文件放在该目录下。 这允许在项目中规范地导入代码。 规范导入是引用完全合格的软件包的导入,例如github.com/digitalocean/godo

Here is what a typical workspace may look like:


├── bin
│   ├── buffalo                                      # command executable
│   ├── dlv                                          # command executable
│   └── packr                                        # command executable
└── src
    └── github.com
        └── digitalocean
            └── godo
                ├── .git                            # Git repository metadata
                ├── account.go                      # package source
                ├── account_test.go                 # test source
                ├── ...
                ├── timestamp.go
                ├── timestamp_test.go
                └── util
                    ├── droplet.go
                    └── droplet_test.go

The default directory for the Go workspace as of 1.8 is your user’s home directory with a go subdirectory, or $HOME/go. If you are using an earlier version of Go than 1.8, it is still considered best practice to use the $HOME/go location for your workspace

从1.8开始,Go工作区的默认目录是用户的主目录,其中带有go子目录,即$HOME/go 。 如果您使用的Go版本早于1.8,则仍认为最佳实践是使用$HOME/go位置作为工作空间。

Issue the following command to navigate to the $HOME directory:


  • cd $HOME

    cd $ HOME

Next, create the directory structure for your Go workspace:


  • mkdir go/bin, go/src

    mkdir go / bin,go / src

This will ensure the following directory structure is now in place:


└── $HOME
    └── go
        ├── bin
        └── src

Prior to Go 1.8, it was required to set a local environment variable called $GOPATH. While it is no longer explicitly required to do so, it is still considered a good practice as many third party tools still depend on this variable being set.

在Go 1.8之前,需要设置一个名为$GOPATH的局部环境变量。 尽管不再明确要求这样做,但由于许多第三方工具仍依赖于此变量的设置,因此仍被视为一种好的做法。

Since you used Chocolatey for the installation, this environment variable should already be set. You can verify this with the following command:

由于您使用Chocolatey进行安装,因此应该已经设置了该环境变量。 您可以使用以下命令对此进行验证:

  • $env:GOPATH

    $ env:GOPATH

You should see the following output, with your username in place of sammy:



When Go compiles and installs tools, it will put them in the $GOPATH/bin directory. For convenience, it’s common to add the workspace’s bin subdirectory to your $PATH. You can do this using the setx command in PowerShell:

当Go编译并安装工具时,它将放置在$GOPATH/bin目录中。 为了方便起见,通常将工作空间的bin子目录添加到$PATH 。 您可以在PowerShell中使用setx命令执行此操作:

  • setx PATH "$($env:path);$GOPATH\bin"

    setx PATH“ $($ env:path); $ GOPATH \ bin”

This will now allow you to run any programs you compile or download via the Go tools anywhere on your system.


Now that you have the root of the workspace created and your $GOPATH environment variable set, you will create your future projects with the following directory structure. This example assumes you are using github.com as your repository:

现在,您已经创建了工作空间的根目录并设置了$GOPATH环境变量, $GOPATH将使用以下目录结构创建将来的项目。 此示例假定您使用github.com作为存储库:


If you were working on the https://github.com/digitalocean/godo project, you would put it in the following directory:



Structuring your projects in this manner will make projects available with the go get tool. It will also help readability later.

以这种方式构建项目将使go get工具可以使用项目。 这也将有助于以后的可读性。

You can verify this by using the go get command to fetch the godo library:

您可以使用go get命令来获取godo库,以进行验证:

  • go get github.com/digitalocean/godo


Note: If you don’t have git installed, Windows will open a dialog box asking if you want to install it. Click Yes to continue and follow the installation instructions.

注意:如果您尚未安装git ,Windows将打开一个对话框,询问您是否要安装它。 单击“ 是”继续并按照安装说明进行操作。

You can see it successfully downloaded the godo package by listing the directory:


  • ls $env:GOPATH/src/github.com/digitalocean/godo

    ls $ env:GOPATH / src / github.com / digitalocean / godo

You will receive output similar to this:


Directory: C:\Users\sammy\go\src\github.com\digitalocean\godo Mode LastWriteTime Length Name ---- ------------- ------ ---- d----- 4/10/2019 2:59 PM util -a---- 4/10/2019 2:59 PM 9 .gitignore -a---- 4/10/2019 2:59 PM 69 .travis.yml -a---- 4/10/2019 2:59 PM 1592 account.go -a---- 4/10/2019 2:59 PM 1679 account_test.go -rw-r--r-- 1 sammy staff 2892 Apr 5 15:56 CHANGELOG.md -rw-r--r-- 1 sammy staff 1851 Apr 5 15:56 CONTRIBUTING.md . . . -a---- 4/10/2019 2:59 PM 5076 vpcs.go -a---- 4/10/2019 2:59 PM 4309 vpcs_test.go

In this step, you created a Go workspace and configured the necessary environment variables. In the next step you will test the workspace with some code.

在此步骤中,您创建了Go工作区并配置了必要的环境变量。 在下一步中,您将使用一些代码来测试工作区。

第6步-创建一个简单程序 (Step 6 — Creating a Simple Program)

Now that you have the Go workspace set up, create a simple “Hello, World!” program. This will make sure that your workspace is configured properly, and also gives you the opportunity to become more familiar with Go. Because you are creating a single Go source file, and not an actual project, you don’t need to be in your workspace to do this.

现在您已经设置了Go工作区,创建一个简单的“ Hello,World!”。 程序。 这将确保您的工作区配置正确,并且还使您有机会更加熟悉Go。 因为您正在创建一个Go源文件,而不是一个实际的项目,所以您不需要在工作区中执行此操作。

From your home directory, open up a command-line text editor, such as nano, and create a new file:


  • nano hello.go

    nano hello.go

Once the text file opens up in nano, type out your program:


package main

import "fmt"

func main() {
    fmt.Println("Hello, World!")

Exit nano by pressing the CTRL and X keys. When prompted to save the file, press Y and then ENTER.

通过按CTRLX键退出nano 。 当提示您保存文件时,按Y ,然后按ENTER

This code will use the fmt package and call the Println function with Hello, World! as the argument. This will cause the phrase Hello, World! to print out to the terminal when the program is run.

该代码将使用fmt包,并使用Hello, World!调用Println函数Hello, World! 作为论点。 这将导致短语Hello, World! 在程序运行时打印到终端。

Once you exit out of nano and return to your shell, run the program:


  • go run hello.go


The hello.go program that you just created should cause PowerShell to produce the following output:


Hello, World!

In this step, you used a basic program to verify that your Go workspace is properly configured.


结论 (Conclusion)

Congratulations! At this point you have a Go programming workspace set up on your local Windows machine and can begin a coding project!

恭喜你! 至此,您已经在本地Windows机器上设置了Go编程工作区,可以开始编码项目!

翻译自: https://www.digitalocean.com/community/tutorials/how-to-install-go-and-set-up-a-local-programming-environment-on-windows-10


  • 0
  • 0
    觉得还不错? 一键收藏
  • 0


  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助




当前余额3.43前往充值 >
领取后你会自动成为博主和红包主的粉丝 规则
钱包余额 0