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 thoroughl