Update day11.md

This commit is contained in:
wenchaoh997 2022-06-16 23:53:49 +08:00
parent 0130fb262d
commit 4352493561

View File

@ -1,36 +1,38 @@
--- ---
title: '#90DaysOfDevOps - Variables & Constants in Go - Day 11' title: '#90DaysOfDevOps - 变量、常量和数据类型 - 第十一天'
published: false published: false
description: 90DaysOfDevOps - Variables & Constants in Go description: 90DaysOfDevOps - 变量、常量和数据类型
tags: 'devops, 90daysofdevops, learning' tags: 'devops, 90daysofdevops, learning'
cover_image: null cover_image: null
canonical_url: null canonical_url: null
id: 1048862 id: 1048862
--- ---
Before we get into the topics for today I want to give a massive shout out to [Techworld with Nana](https://www.youtube.com/watch?v=yyUHQIec83I) and this fantastic concise journey through the fundamentals of Go. 在我们开始今天的学习之前,我想向[Techworld with Nana](https://www.youtube.com/watch?v=yyUHQIec83I)和这段精彩简洁的Go基础之旅欢呼。
On [Day8](day08.md) we set our environment up, on [Day9](day09.md) we walked through the Hello #90DaysOfDevOps code and on [Day10](day10.md)) we looked at our Go workspace and went a little deeper into compiling and running the code. 在[第8天](day08.md)我们设置了环境,[第9天]我们学习了Hello #90DaysOfDevOps 的代码,[第10天]我们查看了Go工作区并更深入了解了编译和运行代码。
Today we are going to take a look into Variables, Constants and Data Types whilst writing a new program. 今天我们要学习变量(Variables),常量(Constants)和数据类型(Data Types),并编写一个新的程序。
## Variables & Constants in Go ## Go中的变量和常量
Let's start by planning our application, I think it would be a good idea to work on a program that tells us how many days we have remained in our #90DaysOfDevOps challenge.
The first thing to consider here is that as we are building our app and we are welcoming our attendees and we are giving the user feedback on the number of days they have completed we might use the term #90DaysOfDevOps many times throughout the program. This is a great use case to make #90DaysOfDevOps a variable within our program. 让我们从规划这个应用程序开始,我觉得开发一个程序是告诉我们#90DaysOfDevOps挑战还有多少天的一个好办法。
- Variables are used to store values. 这里首先要考虑的是,在构建应用程序时,我们欢迎参与者加入,并且我们会向用户反馈当前完成天数。我们将多次用到#90DaysOfDevOps。这是一个很好的例子将#90DaysOfDevOps作为我们程序中的一个变量。
- Like a little box with our saved information or values.
- We can then use this variable across the program which also benefits that if this challenge or variable changes then we only have to change this in one place. Meaning we could translate this to other challenges we have in the community by just changing that one variable value.
To declare this in our Go Program we define a value by using a **keyword** for variables. This will live within our `func main` block of code that you will see later. You can find more about [Keywords](https://go.dev/ref/spec#Keywords)here. - 变量用于存储值
- 类似一个带有信息或数值的盒子
- 后续我们可以在整个程序中使用这个变量,这将在变量发生改变时提供便利,我们只需要在一处改变它的值。这意味着我们可以只改变一个变量值,将其用于社区中的其他挑战中。
Remember to make sure that your variable names are descriptive. If you declare a variable you must use it or you will get an error, this is to avoid possible dead code, code that is never used. This is the same for packages not used. 为了在我们的Go程序中声明变量我们使用一个**关键字**(keyword)来定义一个值。它将存在于我们稍后出现的`func main`代码块中。你可以在[keywords](https://go.dev/ref/spec#Keywords)中查看更多相关信息。
请记住并确保你的变量名是被定义的。如果你声明一个变量,你必须使用它,否则你会得到一个错误。这是为了避免可能出现的无效代码(那些从未被使用的代码)。对于未使用的包也是如此。
``` ```
var challenge = "#90DaysOfDevOps" var challenge = "#90DaysOfDevOps"
``` ```
With the above set and used as we will see in the next code snippet you can see from the output below that we have used a variable.
通过上面的设置,我们会在后续代码片段中使用它,你可以通过下面的输出看到我们已使用这一变量。
``` ```
package main package main
@ -42,15 +44,16 @@ func main() {
fmt.Println("Welcome to", challenge "") fmt.Println("Welcome to", challenge "")
} }
``` ```
You can find the above code snippet in [day11_example1.go](Go/day11_example1.go)
You will then see from the below that we built our code with the above example and we got the output shown below. 你可以在[这里](../../Days/Go/day11_example1.go)找到上述代码片段。
![](Images/Day11_Go1.png) 你会看到我们构建了上述示例代码,并得到下列输出。
We also know that our challenge is 90 days at least for this challenge, but next, maybe it's 100 so we want to define a variable to help us here as well. However, for our program, we want to define this as a constant. Constants are like variables, except that their value cannot be changed within code (we can still create a new app later on down the line with this code and change this constant but this 90 will not change whilst we are running our application) ![](../../Days/Images/Day11_Go1.png)
Adding the `const` to our code and adding another line of code to print this. 我们知道我们的挑战期限是90天但接下来也可能是100天所以我们想去定义一个变量来帮助我们记录。但是在我们的程序中我们想要把它定义为一个常量。常量和变量类似除了它们的值不能被改变(我们会创建一个新的应用并改变这个常量其中90的数值不会改变)。
添加`const`到我们的代码中,并添加一行来打印它。
``` ```
package main package main
@ -65,15 +68,16 @@ func main() {
fmt.Println("This is a", daystotal, "challenge") fmt.Println("This is a", daystotal, "challenge")
} }
``` ```
You can find the above code snippet in [day11_example2.go](Go/day11_example2.go)
If we then go through that `go build` process again and run you will see below the outcome. 你可以在[这里](../../Days/Go/day11_example2.go)找到上述代码。
![](Images/Day11_Go2.png) 如果我们后续再次使用并运行`go build`,你会看到下列输出。
Finally, and this won't be the end of our program we will come back to this in [Day12](day12.md) to add more functionality. We now want to add another variable for the number of days we have completed the challenge. ![](../../Days/Images/Day11_Go2.png)
Below I added `dayscomplete` variable with the number of days completed. 最后,我们将在[第十二天](day12.md)的时候添加其他的功能。现在,我们想加入另外的变量来表示我们已完成这个挑战的天数。
我在下边添加了叫`dayscomplete`的变量,代表完成天数。
``` ```
package main package main
@ -90,17 +94,18 @@ func main() {
fmt.Println("Great work") fmt.Println("Great work")
} }
``` ```
You can find the above code snippet in [day11_example3.go](Go/day11_example3.go)
Let's run through that `go build` process again or you could just use `go run` 你可以在[这里](../../Days/Go/day11_example3.go)找到上述代码。
![](Images/Day11_Go3.png) 再次运行`go build`或者直接使用`go run`。
Here are some other examples that I have used to make the code easier to read and edit. We have up till now been using `Println` but we can simplify this by using `Printf` by using `%v` which means we define our variables in order at the end of the line of code. we also use `\n` for a line break. ![](../../Days/Images/Day11_Go3.png)
I am using `%v` as this uses a default value but there are other options that can be found here in the [fmt package documentation](https://pkg.go.dev/fmt) you can find the code example [day11_example4.go](Go/day11_example4.go) 下面是更容易解读的代码示例。到目前为止,我们用到了`Println`,我们也可以将`Printf`配合`%v`(代表在代码后边的变量)来使用。另外使用`\n`来换行。
Variables may also be defined in a simpler format in your code. Instead of defining that it is a `var` and the `type` you can code this as follows to get the same functionality but a nice cleaner and simpler look for your code. This will only work for variables though and not constants. [这里](../../Days/Go/day11_example4.go)我用到了`%v`来使用默认格式,同时在[fmt package documentation](https://pkg.go.dev/fmt)中也谈到了其他的一些用法。
变量也可以用更简单的方式来定义。除了在定义的时候使用`var`和你可以使用的`type`,下面的代码也可以达到相同的目的,并且能做到更加简洁。这种方法只适用于变量,而不适用于常量(const)。
``` ```
func main() { func main() {
@ -108,53 +113,55 @@ func main() {
const daystotal = 90 const daystotal = 90
``` ```
## Data Types ## 数据类型
In the above examples, we have not defined the type of variables, this is because we can give it a value here and Go is smart enough to know what that type is or at least can infer what it is based on the value you have stored. However, if we want a user to input this will require a specific type.
We have used Strings and Integers in our code so far. Integers for the number of days and strings are for the name of the challenge. 在上述例子中我们并没有定义变量的类型这是因为Go会根据我们输入的值来得知它是什么类型至少它对保存的值有效。然而如果我们想让用户输入特定的数据类型情况又会有所不同。
It is also important to note that each data type can do different things and behaves differently. For example, integers can multiply where strings do not. 我们已经在代码中用到了字符串和整型。整型用来表示天数,字符串用来表示这个挑战的名称。
There are four categories 这里需要关注的,不同的数据类型可以做不一样的事情。例如,整型可以做乘积,而字符串不可以。
- **Basic type**: Numbers, strings, and booleans come under this category. 下面列举了四种类型
- **Aggregate type**: Array and structs come under this category.
- **Reference type**: Pointers, slices, maps, functions, and channels come under this category.
- **Interface type**
The data type is an important concept in programming. Data type specifies the size and type of variable values. - **基础型(Basic type)**,数字(numbers)、字符串(strings)、布尔型(booleans)在这个类别下。
- **聚合型(Aggregate type)**,数组(array)和结构体(structs)在这个类别下。
- **引用型(Reference type)**,指针(pointer)、切片(slices)、集合(maps)、函数(functions)和通道(channels)在这个类别下。
- **接口型(Interface type)**
Go is statically typed, meaning that once a variable type is defined, it can only store data of that type. 数据类型是编程中的一个重要概念。数据类型明确了不同变量的大小和类型。
Go has three basic data types: Go是静态的,这意味着一旦变量的类型被定义了,它只能用于储存该类型的数据。
- **bool**: represents a boolean value and is either true or false Go有三种基本的数据类型
- **Numeric**: represents integer types, floating-point values, and complex types
- **string**: represents a string value
I found this resource super detailed on data types [Golang by example](https://golangbyexample.com/all-data-types-in-golang-with-examples/) - **bool**: 指一个布尔值true或false
- **Numeric**: 指整型、浮点型和复杂型
- **string**: 指一个字符值
I would also suggest [Techworld with Nana](https://www.youtube.com/watch?v=yyUHQIec83I&t=2023s) at this point covers in some detail a lot about the data types in Go. [Golang by example](https://golangbyexample.com/all-data-types-in-golang-with-examples/)给出了很详细的数据类型的例子。
If we need to define a type in our variable we can do this like so: 我也推荐[Techworld with Nana](https://www.youtube.com/watch?v=yyUHQIec83I&t=2023s)里边有谈到许多Go中数据类型的详细内容。
如果我们想去定义一个变量的类型,我们可以做以下操作:
``` ```
var TwitterHandle string var TwitterHandle string
var DaysCompleted uint var DaysCompleted uint
``` ```
Because Go implies variables where a value is given we can print out those values with the following: 因为Go给定了变量一个值我们可以直接打印出来
``` ```
fmt.Printf("challenge is %T, daystotal is %T, dayscomplete is %T\n", conference, daystotal, dayscomplete) fmt.Printf("challenge is %T, daystotal is %T, dayscomplete is %T\n", conference, daystotal, dayscomplete)
``` ```
There are many different types of integer and float types the links above will cover off these in detail.
- **int** = whole numbers 对于整型和浮点型还有许多不同的种类,你可以查看上面提到的链接,阅读更详细的内容。
- **unint** = positive whole numbers
- **floating point types** = numbers that contain a decimal component
## Resources - **int** = 整数
- **unint** = 正整数
- **floating point types** = 含有十进制分量的数
## 相关资料
- [StackOverflow 2021 Developer Survey](https://insights.stackoverflow.com/survey/2021) - [StackOverflow 2021 Developer Survey](https://insights.stackoverflow.com/survey/2021)
- [Why we are choosing Golang to learn](https://www.youtube.com/watch?v=7pLqIIAqZD4&t=9s) - [Why we are choosing Golang to learn](https://www.youtube.com/watch?v=7pLqIIAqZD4&t=9s)
@ -164,6 +171,6 @@ There are many different types of integer and float types the links above will c
- [FreeCodeCamp - Learn Go Programming - Golang Tutorial for Beginners](https://www.youtube.com/watch?v=YS4e4q9oBaU&t=1025s) - [FreeCodeCamp - Learn Go Programming - Golang Tutorial for Beginners](https://www.youtube.com/watch?v=YS4e4q9oBaU&t=1025s)
- [Hitesh Choudhary - Complete playlist](https://www.youtube.com/playlist?list=PLRAV69dS1uWSR89FRQGZ6q9BR2b44Tr9N) - [Hitesh Choudhary - Complete playlist](https://www.youtube.com/playlist?list=PLRAV69dS1uWSR89FRQGZ6q9BR2b44Tr9N)
Next up we are going to start adding some user input functionality to our program so that we are asking how many days have been completed. 接下来我们会开始添加一些用户输入的功能到程序中,我们可以查询已经完成了多少天的挑战。
See you on [Day 12](day12.md). [第十二天](day12.md)见。