如何在Go中编写第一个程序 桃扇骨 2022-11-28 15:21 115阅读 0赞 ### 介绍 **(**Introduction**)** ### The “Hello, World!” program is a classic and time-honored tradition in computer programming. It’s a simple and complete first program for beginners, and it’s a good way to make sure your environment is properly configured. “你好,世界!” 程序是计算机编程中的经典且悠久的传统。 对于初学者来说,这是一个简单而完整的第一个程序,并且是确保正确配置环境的好方法。 This tutorial will walk you through creating this program in Go. However, to make the program more interesting, you’ll modify the traditional “Hello, World!” program so that it asks the user for their name. You’ll then use the name in the greeting. When you’re done with the tutorial, you’ll have a program that looks like this when you run it: 本教程将引导您完成在Go中创建该程序的过程。 但是,为了使程序更有趣,您将修改传统的“ Hello,World!”。 程序,以便它询问用户的姓名。 然后,您将在问候语中使用该名称。 学习完本教程后,您将拥有一个运行该程序的程序,如下所示: Output Please enter your name. Sammy Hello, Sammy! I'm Go! ## 先决条件 **(**Prerequisites**)** ## Before you begin this tutorial, you will need a [local Go development environment][] set up on your computer. You can set this up by following one of these tutorials: 在开始本教程之前,您将需要在计算机上设置[本地Go开发环境][local Go development environment] 。 您可以按照以下教程之一进行设置: * [How to Install Go and Set Up a Local Programming Environment on macOS][] [如何在macOS上安装Go并设置本地编程环境][How to Install Go and Set Up a Local Programming Environment on macOS] * [How to Install Go and Set Up a Local Programming Environment on Ubuntu 18.04][] [如何在Ubuntu 18.04上安装Go并设置本地编程环境][How to Install Go and Set Up a Local Programming Environment on Ubuntu 18.04] * [How to Install Go and Set Up a Local Programming Environment on Windows 10][] [如何在Windows 10上安装Go并设置本地编程环境][How to Install Go and Set Up a Local Programming Environment on Windows 10] ## 第1步-编写基本的“你好,世界!” 程序 **(**Step 1 — Writing the Basic “Hello, World!” Program**)** ## To write the “Hello, World!” program, open up a command-line text editor such as `nano` and create a new file: 写下“你好,世界!” 程序,打开命令行文本编辑器(例如`nano`并创建一个新文件: * nano hello.go nano hello.go Once the text file opens up in the terminal window, you’ll type out your program: 在终端窗口中打开文本文件后,您将输入程序: hello.go 你好 package main import "fmt" func main() { fmt.Println("Hello, World!") } Let’s break down the different components of the code. 让我们分解代码的不同组成部分。 `package` is a Go *keyword* that defines which code bundle this file belongs to. There can be only one package per folder, and each `.go` file has to declare the same package name at the top of its file. In this example, the code belongs to the `main` package. `package`是一个Go *关键字* ,用于定义此文件所属的代码束。 每个文件夹只能有一个程序包,每个`.go`文件必须在其文件顶部声明相同的程序包名称。 在此的示例代码属于`main`包。 `import` is a Go *keyword* that tells the Go compiler which other packages you want to use in this file. Here you import the `fmt` package that comes with the standard library. The `fmt` package provides formatting and printing functions that can be useful when developing. `import`是一个Go *关键字* ,它告诉Go编译器您要在此文件中使用哪些其他软件包。 在这里,您可以导入标准库随附的`fmt`软件包。 `fmt`软件包提供了格式化和打印功能,这些功能在开发时非常有用。 `fmt.Println` is a Go *function*, found in the `fmt` package, that tells the computer to print some text to the screen. `fmt.Println`是`fmt`包中的Go *函数* ,它告诉计算机在屏幕上打印一些文本。 You follow the `fmt.Println` function by a sequence of characters, like `"Hello, World!"`, enclosed in quotation marks. Any characters that are inside of quotation marks are called a *string*. The `fmt.Println` function will print this string to the screen when the program runs. 您在`fmt.Println`函数后跟随一系列字符,例如`"Hello, World!"` ,用引号引起来。 引号内的任何字符都称为*字符串* 。 程序运行时, `fmt.Println`函数会将此字符串打印到屏幕上。 Save and exit `nano` by typing `CTRL + X`, when prompted to save the file, press `Y`. 通过键入`CTRL + X`保存并退出`nano` ,当提示您保存文件时,按`Y` Now you can try your program. 现在您可以尝试您的程序了。 ## 第2步-运行Go程序 **(**Step 2 — Running a Go Program**)** ## With your “Hello, World!” program written, you’re ready to run the program. You’ll use the `go` command, followed by the name of the file you just created. 用你的“你好,世界!” 编写程序后,就可以运行该程序了。 您将使用`go`命令,后跟刚刚创建的文件的名称。 * go run hello.go 去跑hello.go The program will execute and display this output: 程序将执行并显示以下输出: Output Hello, World! Let’s explore what actually happened. 让我们探讨实际发生的情况。 Go programs need to compile before they run. When you call `go run` with the name of a file, in this case `hello.go`, the `go` command will *compile* the application and then run the resulting binary. For programs written in *compiled* programming languages, a compiler will take the source code of a program and generate another type of lower-level code (such as machine code) to produce an executable program. Go程序需要在运行之前进行编译。 当您使用文件名调用`go run`时(在本例中为`hello.go` , `go`命令将*编译*应用程序,然后运行生成的二进制文件。 对于用*编译的*编程语言*编写的*程序,编译器将获取程序的源代码,并生成另一种较低级别的代码(例如,机器代码)以生成可执行程序。 Go applications require a `main` package and exactly **one** `main()` function that serves as the entry point for the application. The `main` function takes no arguments and returns no values. Instead it tells the Go compiler that the package should be compiled as an executable package. Go应用程序需要一个`main`包和**一个** `main()`函数作为该应用程序的入口点。 `main`函数不接受任何参数,也不返回任何值。 相反,它告诉Go编译器该程序包应编译为可执行程序包。 Once compiled, the code executes by entering the `main()` function in the `main` package. It executes the line `fmt.Println("Hello, World!")` by *calling* the `fmt.Println` function. The string value of `Hello, World!` is then *passed* to the function. In this example, the string `Hello, World!` is also called an *argument* since it is a value that is passed to a method. 编译后,通过在`main`包中输入`main()`函数来执行代码。 它通过*调用* `fmt.Println`函数执行`fmt.Println("Hello, World!")` `fmt.Println` 。 `Hello, World!`的字符串值`Hello, World!` 然后*传递*给该函数。 在此示例中,字符串`Hello, World!` 也称为*参数,*因为它是传递给方法的值。 The quotes that are on either side of `Hello, World!` are not printed to the screen because you use them to tell Go where your string begins and ends. `Hello, World!`两侧的引号`Hello, World!` 不会打印到屏幕上,因为您使用它们来告诉Go字符串的开始和结束位置。 In this step, you’ve created a working “Hello, World!” program with Go. In the next step, you will explore how to make the program more interactive. 在此步骤中,您已经创建了一个有效的“ Hello,World!”。 Go编写程序。 在下一步中,您将探索如何使程序更具交互性。 ## 步骤3 —提示用户输入 **(**Step 3 — Prompting for User Input**)** ## Every time you run your program, it produces the same output. In this step, you can add to your program to prompt the user for their name. You’ll then use their name in the output. 每次您运行程序时,它都会产生相同的输出。 在此步骤中,您可以将其添加到程序中,以提示用户输入其名称。 然后,您将在输出中使用它们的名称。 Instead of modifying your existing program, create a new program called `greeting.go` with the `nano` editor: 无需修改现有程序,而是使用`nano`编辑器创建一个名为`greeting.go`的新程序: * nano greeting.go 纳米greeting.go First, add this code, which prompts the user to enter their name: 首先,添加以下代码,提示用户输入其名称: greeting.go greeting.go package main import ( "fmt" ) func main() { fmt.Println("Please enter your name.") } Once again, you use the `fmt.Println` function to print some text to the screen. 再次使用`fmt.Println`函数将一些文本打印到屏幕上。 Now add the highlighted line to store the user’s input: 现在添加突出显示的行以存储用户的输入: greeting.go greeting.go package main import ( "fmt" ) func main() { fmt.Println("Please enter your name.") var name string } The `var name string` line will create a new variable using the `var` *keyword*. You name the variable `name`, and it will be of type `string`. `var name string`行将使用`var` *关键字*创建一个新变量。 您命名变量`name` ,它将是`string`类型。 Then, add the highlighted line to capture the user’s input: 然后,添加突出显示的行以捕获用户的输入: greeting.go greeting.go package main import ( "fmt" ) func main() { fmt.Println("Please enter your name.") var name string fmt.Scanln(&name) } The `fmt.Scanln` method tells the computer to wait for input from the keyboard ending with a new line or (`\n`), character. This pauses the program, allowing the user to enter any text they want. The program will continue when the user presses the `ENTER` key on their keyboard. All of the keystrokes, including the `ENTER` keystroke, are then captured and converted to a string of characters. `fmt.Scanln`方法告诉计算机等待键盘输入以新行或( `\n` )字符结尾的输入。 这将暂停程序,允许用户输入所需的任何文本。 当用户按键盘上的`ENTER`键时,程序将继续。 然后捕获所有击键,包括`ENTER`击键,并将其转换为字符串。 You want to use those characters in your program’s output, so you save those characters by *writing* them into the string *variable* called `name`. Go stores that string in your computer’s memory until the program finishes running. 您想在程序的输出中使用这些字符,因此可以通过*将*它们写入名为`name`的字符串*变量中来*保存这些字符。 Go将该字符串存储在计算机的内存中,直到程序运行完毕。 Finally, add the following highlighted line in your program to print the output: 最后,在程序中添加以下突出显示的行以打印输出: greeting.go greeting.go package main import ( "fmt" ) func main() { fmt.Println("Please enter your name.") var name string fmt.Scanln(&name) fmt.Printf("Hi, %s! I'm Go!", name) } This time, instead of using the `fmt.Println` method again, you’re using `fmt.Printf`. The `fmt.Printf` function takes a string, and using special printing *verbs*, (`%s`), it injects the value of `name` into the string. You do this because Go does not support *string interpolation*, which would let you take the value assigned to a variable and place it inside of a string. 这次,您将使用`fmt.Printf` ,而不是再次使用`fmt.Println`方法。 `fmt.Printf`函数采用字符串,并使用特殊的打印*动词* ( `%s` )将`name`的值注入字符串中。 这样做是因为Go不支持*字符串插值* ,这会使您获取分配给变量的值并将其放在字符串中。 Save and exit `nano` by pressing `CTRL + X`, and press `Y` when prompted to save the file. 通过按`CTRL + X`保存和退出`nano` ,然后在提示保存文件时按`Y` Now run the program. You’ll be prompted for your name, so enter it and press `ENTER`. The output might not be exactly what you expect: 现在运行程序。 系统将提示您输入名称,因此输入名称并按`ENTER` 。 输出结果可能与您的预期不完全相同: Output Please enter your name. Sammy Hi, Sammy ! I'm Go! Instead of `Hi, Sammy! I'm Go!`, there’s a line break right after the name. `Hi, Sammy! I'm Go!`而不是`Hi, Sammy! I'm Go!` `Hi, Sammy! I'm Go!` ,名称后面有一个换行符。 The program captured **all** of our keystrokes, including the `ENTER` key that we pressed to tell the program to continue. In a string, pressing the `ENTER` key creates a special character that creates a new line. The program’s output is doing exactly what you told it to do; it’s displaying the text you entered, including that new line. It’s not what you expected the output to be, but you can fix it with additional functions. 该程序捕获了我们**所有**的击键,包括我们按下以告知程序继续的`ENTER`键。 在字符串中,按`ENTER`键将创建一个特殊字符,该字符将创建新行。 程序的输出完全按照您的指示执行。 它会显示您输入的文本,包括新行。 这不是您期望的输出,但是您可以使用其他功能对其进行修复。 Open the `greeting.go` file in your editor: 在编辑器中打开`greeting.go`文件: * nano greeting.go 纳米greeting.go Locate this line in your program: 在程序中找到以下行: greeting.go greeting.go ... fmt.Scanln(&name) ... Add the following line right after it: 在其后添加以下行: greeting.go greeting.go name = strings.TrimSpace(name) This uses the `TrimSpace` function, from Go’s standard library `strings` package, on the string that you captured with `fmt.Scanln`. The `strings.TrimSpace` function removes any space characters, including new lines, from the start and end of a string. In this case, it removes the newline character at the end of the string created when you pressed `ENTER`. 本品采用`TrimSpace`功能,从Go的标准库`strings`包,在您与拍摄到的字符串`fmt.Scanln` 。 `strings.TrimSpace`函数从`strings.TrimSpace`的开头和结尾删除所有空格字符,包括换行符。 在这种情况下,它将在按`ENTER`时创建的字符串末尾删除换行符。 To use the `strings` package you need to import it at the top of the program. 要使用`strings`包,您需要将其导入程序顶部。 Locate these lines in your program: 在程序中找到以下几行: greeting.go greeting.go import ( "fmt" ) Add the following line to import the `strings` package: 添加以下行以导入`strings`包: greeting.go greeting.go import ( "fmt" "strings" ) Your program will now contain the following: 您的程序现在将包含以下内容: greeting.go greeting.go package main import ( "fmt" "strings" ) func main() { fmt.Println("Please enter your name.") var name string fmt.Scanln(&name) name = strings.TrimSpace(name) fmt.Printf("Hi, %s! I'm Go!", name) } Save and exit `nano`. Press `CTRL + X`, then press `Y` when prompted to save the file. 保存并退出`nano` 。 按`CTRL + X` ,然后在提示保存文件时按`Y` Run the program again: 再次运行程序: * go run greeting.go 去运行greeting.go This time, after you enter your name and press `ENTER`, you get the expected output: 这次,在输入名称并按`ENTER` ,将获得预期的输出: Output Please enter your name. Sammy Hi, Sammy! I'm Go! You now have a Go program that takes input from a user and prints it back to the screen. 现在,您有了一个Go程序,该程序可以接受用户的输入并将其打印回屏幕。 ## 结论 **(**Conclusion**)** ## In this tutorial, you wrote a “Hello, World!” program that takes input from a user, processes the results, and displays the output. Now that you have a basic program to work with, try to expand your program further. For example, ask for the user’s favorite color, and have the program say that its favorite color is red. You might even try to use this same technique to create a simple Mad-Lib program. 在本教程中,您写了一个“ Hello,World!”。 从用户处获取输入,处理结果并显示输出的程序。 现在您已经可以使用一个基本程序,请尝试进一步扩展程序。 例如,询问用户喜欢的颜色,并让程序说它喜欢的颜色是红色。 您甚至可以尝试使用相同的技术来创建简单的Mad-Lib程序。 > 翻译自: [https://www.digitalocean.com/community/tutorials/how-to-write-your-first-program-in-go][https_www.digitalocean.com_community_tutorials_how-to-write-your-first-program-in-go] [local Go development environment]: https://www.digitalocean.com/community/tutorial_series/how-to-install-and-set-up-a-local-programming-environment-for-go [How to Install Go and Set Up a Local Programming Environment on macOS]: https://www.digitalocean.com/community/tutorials/how-to-install-go-and-set-up-a-local-programming-environment-on-macos [How to Install Go and Set Up a Local Programming Environment on Ubuntu 18.04]: https://www.digitalocean.com/community/tutorials/how-to-install-go-and-set-up-a-local-programming-environment-on-ubuntu-18-04 [How to Install Go and Set Up a Local Programming Environment on Windows 10]: https://www.digitalocean.com/community/tutorials/how-to-install-go-and-set-up-a-local-programming-environment-on-windows-10 [https_www.digitalocean.com_community_tutorials_how-to-write-your-first-program-in-go]: https://www.digitalocean.com/community/tutorials/how-to-write-your-first-program-in-go
还没有评论,来说两句吧...