jav101上不去
Similarly to mathematics, variables, in computer science, are placeholders that hold a value (to be more precise, a location that points to a value). Those variables are associated to four elements: a keyword, a name, a type and a value. Those variables are particularly useful in order to avoid dealing directly with literal values (like numbers, strings or booleans), but also to hold a value that we might want to use later on in our program. Besides variables, Go also offers the possibility to use constants. Similarly to variables, constants hold different kind of values. However, those values won’t be able to be changed during the execution of our program.
与数学类似,计算机科学中的变量是保存值的占位符(更精确地说,是指向值的位置)。 这些变量与四个元素关联: 关键字 , 名称 , 类型和值 。 这些变量特别有用,它可以避免直接处理文字值(例如数字,字符串或布尔值),而且还可以保存我们稍后可能在程序中使用的值。 除了变量外,Go还提供了使用常量的可能性。 与变量类似,常量具有不同类型的值。 但是,在执行程序期间将无法更改这些值。
Finally, we will go through the concept of scope. The scope defines where our variables and constants can be accessed. We will see that Go is characterised by a lexical scope, defined by curly brackets (even tough we have already seen that Go has its own specificity, its package scope that we will see more in details when learning about functions).
最后,我们将讨论范围的概念。 范围定义了可以在哪里访问变量和常量。 我们将看到Go的特征是用大括号定义的词法范围(即使很难理解,Go也有其自身的特殊性,我们在学习函数时会更详细地了解它的包范围 )。
变数 (Variables)
As mentioned in the introduction, a variable is characterised by four parameters: a keyword, a name, a type and a value.
如引言中所述,变量的特征在于四个参数: 关键词 , 名称 , 类型和值 。
In Go, variable definition starts with the var keyword. As we will see, this keyword is actually optional in most of the cases, and is thus usually forgotten in the idiomatic usage of the language.
在Go中,变量定义以var关键字开头。 正如我们将看到的,在大多数情况下,该关键字实际上是可选的,因此通常在该语言的惯用用法中忘记该关键字。
The name, chosen during the variable definition, is used to access our variable later on. In Go, there is a set of rules that should be followed in order to correctly name a variable. Names should always start with a letter. The following characters can either be other letters, numbers or underscore characters. In addition, naming should always uses the camel case style for compound names (for example, minNumber).
在变量定义期间选择的名称 ,以后将用于访问我们的变量。 在Go中,必须遵循一组规则才能正确命名变量。 名称应始终以字母开头 。 以下字符可以是其他字母,数字或下划线字符。 另外,命名应始终使用驼峰式大小写形式来表示化合物名称(例如, minNumber )。
As Go is a statically-typed language, each variable needs to be assigned a data type when being defined. Those types can be any of the types we have seen so far (string, number, boolean) or any other more complex types that we will see later on. This step is important as, as you know, the type assigned to a variable cannot be changed later on in our program. This feature forces us to think thoroughly about the design of our program beforehand, thus allowing us to create better designed program.
由于Go是一种静态类型的语言,因此在定义每个变量时都需要为其分配一种数据 类型 。 这些类型可以是我们到目前为止所见的任何类型 (字符串,数字,布尔值),也可以是我们稍后将看到的任何其他更复杂的类型。 如您所知,此步骤很重要,因为稍后在我们的程序中无法更改分配给变量的类型。 此功能迫使我们事先仔细考虑程序的设计,从而使我们可以创建更好的设计程序。
Finally, our variable needs to be assigned a value. This value can be a literal value (for example, 1 or “Hello, World!”), but also any another variable or constant. This value assignment is independent from the variable definition (keyword, name and type) and can actually be performed later on in the program.
最后,我们的变量需要分配一个值 。 该值可以是文字值 (例如1或“ Hello,World!” ),也可以是任何其他变量或常量。 此值分配与变量定义(关键字,名称和类型) 无关 ,并且实际上可以稍后在程序中执行。
Programmatically, a variable is thus defined as followed,
因此,以编程方式将变量定义如下:
var hello string = "Hello, variable!"
We indeed have here our var keyword, the name of our variable (hello), the type of our value (string) and the actual value (“Hello, variable!”). As mentioned earlier, we could have divided the definition and assignment into two lines.
实际上,这里确实有我们的var关键字,变量名( hello ),值的类型( string )和实际值( “ Hello,variable!” )。 如前所述,我们可以将定义和赋值分为两行。
var hello string
hello = "Hello, variable!" /* We use the name of our variable to assign it a value, with the = sign */
A variable, as the name suggests, can have its value changed (but not its type) along the execution of our program. To do that, you just need to reassign a value to the variable, as followed.
顾名思义,变量可以更改其值 (但不能更改其类型) 随着我们程序的执行 为此,您只需要为变量重新分配一个值,如下所示。
var x string = "Original value"
x = "Substituted value"
fmt.Println(x)// This will print Substituted value to the console
If we would run this program, the program would output Substituted value to the console, which is indeed the value that we reassigned to our variable x in the second line of our program.
如果我们要运行该程序,则该程序会将替代值输出到控制台,这实际上是我们在程序第二行中重新分配给变量x的值。
In reality, there are shorter ways to define a variable, which should be used as a convention (whenever it is possible).
实际上,定义变量的方法较短 ,应将其用作约定(只要有可能)。
Firstly, we could remove the type part of our definition. Go’s compiler is indeed capable of inferring the type of a variable by looking at the value that is being given to it. However, this only works if we define our variable and assign it a value on the same line (the program won’t compile otherwise). This process would look like as follow,
首先,我们可以删除定义的类型部分。 Go的编译器确实能够通过查看赋给变量的值来推断变量的类型。 但是,这仅在定义变量并在同一行为其分配值的情况下才有效(否则程序将无法编译)。 此过程如下所示,
var hello = "Hello, variable!" // Go will infer that our variable is of a string type
There is however a way to shorten it even more, by removing the keyword var (but, changing the assignment operator from = to :=). Again, we can use this way only if we define our variable and assign it a value on the same line. The process would then look like the following one.
但是,可以通过删除关键字 var (甚至将赋值运算符从=更改为:= )来进一步缩短它。 同样,只有在定义变量并在同一行上为其分配值时,我们才能使用这种方式。 然后,该过程将类似于以下过程。
hello := "Hello, variable!"
This way is shorter than the previous one and is used as a convention whenever it is possible to use it.
这种方式比前一种方式短,并且只要有可能就用作惯例。
常数 (Constants)
Similarly to variables, constants are made of four elements: a keyword, a name, a type and a value. However, and as the name suggests, once we assigned a value to a constant, this value cannot be changed later on. Thus, it makes them very useful to hold values such as mathematics constants, or any other values that is meant to stay constant throughout the execution of your program.
与变量类似,常量由四个元素组成: 关键字 , 名称 , 类型和值 。 但是,顾名思义,一旦我们为常数分配了一个值,此值以后就无法更改。 因此,这对于保存诸如数学常数之类的值或在程序执行过程中保持不变的任何其他值非常有用。
To define a constant, you will need to use the const keyword, as followed.
要定义一个常量,您将需要使用const关键字,如下所示。
const pi float64 = 3.1416
As the value of a constant cannot change, redefining pi to any other value would produce a compiling error.
由于常量的值不能更改 ,因此将pi重新定义为任何其他值将产生编译错误。
Similarly to variables, it exists a shorthanded version for defining a constant, by removing the type part (however, it is not possible to remove the const keyword, as Go would then use a variable by default).
与变量类似,它也存在一个简化版本,用于通过删除类型部分来定义常量(但是,无法删除const关键字,因为Go会默认使用变量)。
const pi = 3.1416
多重定义 (Multiple definition)
Similarly to other programming languages, it is possible to define multiple variables (or constants) at the same time, as shown below.
类似于其他编程语言,可以同时定义多个变量(或常量),如下所示。
var (
first = "I"
second = "love"
third = "Go."
)
It is important to notice several things. Firstly, each variable (or constant) should be on its own line. Secondly, we voluntarily omitted the type (in this case, string) after the name of each variable, but it would be totally valid to use it. Lastly, as we use the keyword var (const for constants), we use the = sign (and not the := sign).
注意几件事很重要。 首先,每个变量(或常量)应位于其自己的行上 。 其次,我们自愿省略了每个变量名称之后的类型 (在这种情况下为string ),但是使用它是完全有效的。 最后,由于我们使用关键字var ( 常量表示const ),因此使用=符号(而不是:=符号)。
范围 (Scope)
In programming, a scope defines the range in which we can access a variable (or constant). Even though explaining scope in details is not part of this tutorial, the basic idea behind it is to avoid two things. Firstly, we want to avoid naming conflict (trying to define a variable with a name that already exists in our program, and thus reassigning the value of the first variable unintentionally). The second reason, consequence of the first one, is that we want to avoid reassigning unintentionally a value to a variable in another part of the program, and then creating unexpected behaviour from our program.
在编程中,范围定义了我们可以访问变量 (或常量)的范围。 即使详细解释范围不是本教程的一部分,但其背后的基本思想是避免两件事。 首先,我们要避免命名冲突 (尝试使用程序中已经存在的名称定义变量,从而无意中重新分配第一个变量的值)。 第二个原因是第一个原因,我们要避免在程序的另一部分中无意中将值分配给变量,然后在程序中创建意外行为。
To avoid those issues, Go is using what we call a lexical (or static) scope. In other words, this means that the place where we can access a variable depends on the place where this variable is defined in the first place (as opposed to a dynamic scope where we would access a variable defined in what is calling our function).
为了避免这些问题,Go使用了我们所谓的词汇 (或静态)范围。 换句话说,这意味着我们可以访问变量的位置取决于首先定义此变量的位置 (与动态范围相反,在动态范围中,我们将访问在调用函数中定义的变量)。
In Go, this scope is restricted by a block, block itself defined by curly braces. In other words, a variable (or constant) can only be accessed in the block in which it is defined, or in any child scope. This includes for example a variable defined inside a function (which is thus accessible everywhere inside that function, but not outside of it), but also, as we will see later, inside a conditional block. It is also worth mentioning that a variable (or constant) defined inside the global scope (outside of any functions or conditional blocks) will be accessible everywhere in our program, as this represents the parent scope of all other scopes defined in our module.
在Go中,此范围受block限制,block本身由花括号定义。 换句话说,变量(或常量)只能在定义它的块中或在任何子作用域中访问。 例如,这包括一个在函数内部定义的变量(因此可以在该函数内部的任何地方访问,但不能在函数外部访问),而且如稍后将看到的,在条件块内部也可以访问。 还值得一提的是,在全局范围内定义的变量(或常量)(在任何函数或条件块之外)将可以在程序中的任何位置访问 ,因为它表示模块中定义的所有其他范围的父范围。
In order to illustrate this concept, let’s use the following two programs.
为了说明这个概念,让我们使用以下两个程序。
package main
import "fmt"
var x = "Hello, Scope!"
func main() {
fmt.Println(x)
testScope()
}
func testScope() {
fmt.Println(x, "test")
}
// This will print "Hello, Scope!" and "Hello, Scope! test" To the console
In this program, we define two functions. The first one, main, will access our variable x defined in the global scope (be careful in this circumstance that the variable or constant in the global scope needs to be defined using the corresponding keyword), as well as calling our second function. This second function, testScope access the same global variable, and print it to the console too (with a “test” string concatenated to it, to differentiate it from the output from the main function).
在此程序中,我们定义了两个功能。 第一个主变量将访问我们在全局范围内定义的变量x(在这种情况下,请注意需要使用相应的关键字定义全局范围内的变量或常量),并调用第二个函数。 第二个函数testScope访问相同的全局变量,并将其也打印到控制台(带有连接到其的“ test”字符串,以将其与主函数的输出区分开)。
package main
import "fmt"
func main() {
x := "Hello, Scope!"
fmt.Println(x)
testScope()
}
func testScope() {
fmt.Println(x, "test")
}
// This program won't compile, as x is undefined in the testScope function
In this program, we define the variable x inside the main function and we then output it to the console. We also call the testScope function that tries to print x to the console as well. However, doing so will create a compiling error, as x is undefined in the scope of the testScope function. Indeed, x is defined inside the block of the main function, and can thus only be accessible inside that same block (thus, not in any other function).
在此程序中,我们在主函数中定义变量x ,然后将其输出到控制台。 我们还调用了testScope函数,该函数也尝试将x打印到控制台。 但是,这样做会产生编译错误,因为x在testScope函数的范围内未定义 。 实际上, x是在主函数的块内部定义的,因此只能在同一块内部访问(因此,不能在任何其他函数中访问)。
In this tutorial, we have been continuing our journey through the basic concepts of Go. We have indeed explored the concepts of variables, constants and scopes. Those concepts are fundamental to understand the more advanced parts of the language, parts that we will start learning in the tutorials to come, after we make a last stop in the basics part of the language: conditional flow.
在本教程中,我们将继续学习Go的基本概念。 我们确实已经探索了变量,常量和范围的概念。 这些概念是理解语言更高级部分的基础,这些是我们在语言的基础部分最后停下来之后将在以后的教程中开始学习的部分:条件流。
I hope you have enjoyed this tutorial, and as always, please refer to the comments section for any questions you could have.
我希望您喜欢本教程,并且像往常一样,如有任何问题,请参阅评论部分。
资源资源 (Resources)
In this section, you can find a link to all the resources we have been using in this tutorial.
在本部分中,您可以找到我们在本教程中一直在使用的所有资源的链接。
Link to our introduction tutorial: https://medium.com/better-programming/go-101-hello-world-3f56e7b1146c
链接到我们的入门教程: https : //medium.com/better-programming/go-101-hello-world-3f56e7b1146c
Link to our types tutorial: https://medium.com/the-innovation/go-101-a3d85c58676f
链接到我们的类型教程: https : //medium.com/the-innovation/go-101-a3d85c58676f
Gist with the global variable: https://gist.github.com/Agilulfe/c7593b2253fc3a825d4e70e4dbea3e36
要点与全局变量: https : //gist.github.com/Agilulfe/c7593b2253fc3a825d4e70e4dbea3e36
Gist with the undefined error: https://gist.github.com/Agilulfe/c3eb4fc340615a29e99f92a2748bf582
要点带有未定义的错误: https : //gist.github.com/Agilulfe/c3eb4fc340615a29e99f92a2748bf582
Gist will all the code from this tutorial: https://gist.github.com/Agilulfe/5596835a314423cc746c8a7426130dbe
要点将提供本教程中的所有代码: https : //gist.github.com/Agilulfe/5596835a314423cc746c8a7426130dbe
jav101上不去